Skip to content

Content Server (OTCS)

OTCS Module to implement functions to read / write Content Server objects such as Users, Groups, Nodes, Workspaces, ...

Class: OTCS

Class Methods:

date_is_newer: Compare two dates, typically create or modification dates

Methods:

init: class initializer config: returns config data set cookie: returns cookie information otcs_ticket: Return the OTCS ticket credentials: Get credentials (username and password) set_credentials: Set new credentials hostname: Get the configured OTCS hostname set_hostname: Set the hostname of OTCS base_url: Get OTCS base URL cs_url: Get the Extended ECM (OTCS) URL rest_url: Get OTCS REST base URL

get_data: Get the Data object that holds all loaded Content Server items (see method load_items())

request_form_header: Deliver the request header used for the CRUD REST API calls. request_json_header: Deliver the request header for REST calls that require content type application/json. request_download_header: Deliver the request header used for download REST API calls. These calls accept application/octet-stream. do_request: call an Extended ECM REST API in a safe way. parse_request_response: Converts the text property of a request response object to a Python dict in a safe way lookup_result_value: Lookup a property value based on a provided key / value pair in the response properties of an Extended ECM REST API call exist_result_item: Check existence of key / value pair in the response properties of an Extended ECM REST API call. get_result_value: Read an item value from the REST API response. This is considering the most typical structures delivered by V2 REST API of Extended ECM

is_configured: returns true if the OTCS pod is ready to serve requests authenticate : Authenticates at Content Server and retrieve OTCS Ticket.

get_server_info: return OTCS server information

apply_config: Apply Content Server administration settings from XML file

get_user: Lookup Content Server user add_user: Add Content Server user search_user: Find a user based on search criteria update_user: Update a defined field for a user get_user_profile: Get the profile (settings) for the current user update_user_profile: Update a defined field of the user profile (settings) for the current user. update_user_photo: Update a user with a profile photo (which must be an existing node) is_proxy: Check if a user (login name) is a proxy of the current user get_user_proxies: Get the list of proxy users for the current user add_user_proxy: Add a proxy to the current (authenticated) user add_favorite: Add a favorite for the current (authenticated) user add_favorite_tab: Add a favorite tab for the current (authenticated) user

get_group: Lookup Content Server group add_group: Add Content Server group get_group_members: Get Content Server group members add_group_member: Add a user or group to a target group

get_node: Get a node based on the node ID get_node_by_parent_and_name: Get a node based on the parent ID and name get_node_by_workspace_and_path: Get a node based on the workspace ID and path (list of folder names) get_node_by_volume_and_path: Get a node based on the volume ID and path get_node_from_nickname: Get a node based on the nickname set_node_nickname: Assign a nickname to an Extended ECM node (e.g. workspace) get_subnodes: get children nodes of a parent node lookup_node: lookup the node under a parent node that has a specified value in a category attribute. get_node_columns: get custom columns configured / enabled for a node. get_node_actions: get possible actions for a node rename_node: Change the name and description of a node delete_node: Delete a node purge_node: Delete a node from the recycle bin restore_node: Restore a node from the recycle bin get_volumes: Get all Volumes get_volume: Get Volume information based on the volume type ID check_node_name: Check if a a node name in a parent location has a name collision

Fetch a file from a URL or local filesystem and upload

it to an Extended ECM volume

upload_file_to_parent: Upload a document to a parent folder add_document_version: Add a version to an Extended ECM document get_latest_document_version: Get latest version of a document node based on the node ID. get_document_content: get content of a document version get_json_document: Get document content from Extended ECM and read content as JSON. download_document: Download a document download_config_file: Download a config file from a given OTCS URL. This is NOT for downloading documents from within the OTCS repository

search: search for a search term using Extended ECM search engine

get_external_system_connection: Get Extended ECM external system connection add_external_system_connection: Add Extended ECM external system connection

create_transport_workbench: Create a Workbench in the Transport Volume unpack_transport_package: Unpack an existing Transport Package into an existing Workbench deploy_workbench: Deploy an existing Workbench deploy_transport: Main method to deploy a transport. This uses subfunctions to upload, unpackage and deploy the transport, and creates the required workbench replace_transport_placeholders: Search and replace strings in the XML files of the transport packlage

get_business_object_types: Get information for all configured business object types get_business_object_type: Get information for a specific business object type get_business_objects: Get all business objects for an external system and a given business object type.

get_workspace_types: Get all workspace types configured in Extended ECM get_workspace_create_form: Get the Workspace create form get_workspace: Get a workspace node get_workspace_instances: Get all instances of a given workspace type get_workspace_by_type_and_name: Lookup workspace based on workspace type name and workspace name get_workspace_type_location: Determine the folder in which the workspace instances of a given type reside. Either the type ID or the type name need to be provided. get_workspace_by_business_object: Lookup workspace based by an business object of an external system set_workspace_reference: Set reference of workspace to a business object in an external system create_workspace: Create a new business workspace update_workspace: Update the metadata of a workspace create_workspace_relationship: Create a relationship between two workspaces get_workspace_relationships: get a list of related workspaces get_workspace_roles: Get the Workspace roles add_workspace_member: Add member to workspace role. Check that the user is not yet a member remove_workspace_member: Remove member from workspace role remove_workspace_members: Remove all members from a workspace role. Check that the user is currently a member. assign_workspace_permissions: Update workspace permissions for a given role update_workspace_icon: Update a workspace with a with a new icon (which is uploaded)

get_unique_names: Get information on definition of Unique Names.

create_item: Create an item in Extended ECM (e.g. folder or URL item) update_item: Update an item in Extended ECM (e.g. folder or URL item) get_document_templates: Get all document templates for a given target location create_document_from_template: Create a document based on a document template create_wiki: Create an Extended ECM Wiki. create_wiki_page: Create an Extended ECM wiki page.

get_web_report_parameters: Get parameters of a Web Report run_web_report: Run a Web Report that is identified by its nick name

install_cs_application: Install a CS Application (based on WebReports)

assign_item_to_user_group: Assign an item (e.g. Workspace or document) to a list of users or groups

convert_permission_string_to_permission_value: Convert a list of permission names to a permission value convert_permission_value_to_permission_string: Convert a permission value to a list of permission strings assign_permission: Assign permissions to an item for a defined user or group

get_node_categories: Get categories assigned to a node get_node_category: Get a specific category assigned to a node get_node_category_ids: Get list of all category definition IDs that are assign to the node. get_node_category_names: Get list of all category names that are assign to the node. get_node_category_definition: Get category definition (category id and attribute IDs and types) assign_category: Assign a category to a node get_category_value_by_name: Lookup the value of an attribute if category name, set name and attribute name are known. get_category_value: Lookup the value of an attribute if category ID, set ID and attribute ID are known. If you only have the names use get_category_value_by_name() set_category_value: Set a value for a specific category attribute to a node set_category_values: Set values of a category. Categories and have sets (groupings), multi-line sets (matrix), and multi-value attributes (list of values). This method supports all variants. set_category_inheritance: Set if we want a container item (e.g. a folder or workspace) to inherit categories to sub-items.

assign_classification: Assign a classification to an item assign_rm_classification: Assign a Records management classification to an item

register_workspace_template: Register a workspace template for Extended ECM for Engineering

get_records_management_rsis: Get the ist of RSIs together with their RSI schedules get_records_management_codes: Get Records Management Codes update_records_management_codes: Update the Records Management Codes create_records_management_rsi: Create a new Records Management RSI item create_records_management_rsi_schedule: Create a schedule for an existing RSI item create_records_management_hold: Create a Records Management Hold get_records_management_holds: Get a list of all Records Management Holds in the system. import_records_management_codes: Import RM codes from a config file import_records_management_rsis: Import RM RSIs from a config file import_records_management_settings: Import Records Management settings from a config file import_physical_objects_codes: Import Physical Objects codes from a config file import_physical_objects_settings: Import Physical Objects settings from a config file import_physical_objects_locators: Import Physical Objects locators from a config file import_security_clearance_codes: Import Securioty Clearance codes from a config file

assign_user_security_clearance: Assign a Security Clearance level to a user assign_user_supplemental_markings: Assign a list of Supplemental Markings to a user

get_workflow_definition: Get the workflow definition get_workflow_attributes: Get workflow attribute definition. get_document_workflows: Get a list of aviable workflows for a document ID and a parent ID get_workflows_by_kind_and_status: Get a list of workflows with a defined status get_workflow_status: Get the status (task list) of a workflow instance (process) create_draft_process: Create an Extended ECM workflow as a draft process update_draft_process: Update a draft process with values. These can either be given via dedicated parameters like title and due_date or with a generic value dictionary. initiate_draft_process: Initiate an Extended ECM workflow instance from a draft process get_process_task: Get the task information of a workflow assignment. update_process_task: Update a process with values in a task. This method needs to be called with the user that has the task in its inbox (My ToDo - Workflows). It can update the task data (formUpdate) and/or send on the task to the next workflow step (action or custom_action).

check_workspace_aviator: Check if Content Aviator is enabled for a workspace update_workspace_aviator: Enable or disable the Content Aviator for a workspace

Experimental code to translate the item names and item descriptions in a given hierarchy.

The actual translation is done by a tranlator object. This recursive method just traverses the hierarchy and calls the translate() method of the translator object.

download_document_multi_threading: Multi-threading variant of download_document() load_items: Create a Pandas Data Frame by traversing a given Content Server hierarchy and collecting workspace and document items.

OTCS

Used to automate stettings in OpenText Extended ECM.

Source code in pyxecm/otcs.py
  274
  275
  276
  277
  278
  279
  280
  281
  282
  283
  284
  285
  286
  287
  288
  289
  290
  291
  292
  293
  294
  295
  296
  297
  298
  299
  300
  301
  302
  303
  304
  305
  306
  307
  308
  309
  310
  311
  312
  313
  314
  315
  316
  317
  318
  319
  320
  321
  322
  323
  324
  325
  326
  327
  328
  329
  330
  331
  332
  333
  334
  335
  336
  337
  338
  339
  340
  341
  342
  343
  344
  345
  346
  347
  348
  349
  350
  351
  352
  353
  354
  355
  356
  357
  358
  359
  360
  361
  362
  363
  364
  365
  366
  367
  368
  369
  370
  371
  372
  373
  374
  375
  376
  377
  378
  379
  380
  381
  382
  383
  384
  385
  386
  387
  388
  389
  390
  391
  392
  393
  394
  395
  396
  397
  398
  399
  400
  401
  402
  403
  404
  405
  406
  407
  408
  409
  410
  411
  412
  413
  414
  415
  416
  417
  418
  419
  420
  421
  422
  423
  424
  425
  426
  427
  428
  429
  430
  431
  432
  433
  434
  435
  436
  437
  438
  439
  440
  441
  442
  443
  444
  445
  446
  447
  448
  449
  450
  451
  452
  453
  454
  455
  456
  457
  458
  459
  460
  461
  462
  463
  464
  465
  466
  467
  468
  469
  470
  471
  472
  473
  474
  475
  476
  477
  478
  479
  480
  481
  482
  483
  484
  485
  486
  487
  488
  489
  490
  491
  492
  493
  494
  495
  496
  497
  498
  499
  500
  501
  502
  503
  504
  505
  506
  507
  508
  509
  510
  511
  512
  513
  514
  515
  516
  517
  518
  519
  520
  521
  522
  523
  524
  525
  526
  527
  528
  529
  530
  531
  532
  533
  534
  535
  536
  537
  538
  539
  540
  541
  542
  543
  544
  545
  546
  547
  548
  549
  550
  551
  552
  553
  554
  555
  556
  557
  558
  559
  560
  561
  562
  563
  564
  565
  566
  567
  568
  569
  570
  571
  572
  573
  574
  575
  576
  577
  578
  579
  580
  581
  582
  583
  584
  585
  586
  587
  588
  589
  590
  591
  592
  593
  594
  595
  596
  597
  598
  599
  600
  601
  602
  603
  604
  605
  606
  607
  608
  609
  610
  611
  612
  613
  614
  615
  616
  617
  618
  619
  620
  621
  622
  623
  624
  625
  626
  627
  628
  629
  630
  631
  632
  633
  634
  635
  636
  637
  638
  639
  640
  641
  642
  643
  644
  645
  646
  647
  648
  649
  650
  651
  652
  653
  654
  655
  656
  657
  658
  659
  660
  661
  662
  663
  664
  665
  666
  667
  668
  669
  670
  671
  672
  673
  674
  675
  676
  677
  678
  679
  680
  681
  682
  683
  684
  685
  686
  687
  688
  689
  690
  691
  692
  693
  694
  695
  696
  697
  698
  699
  700
  701
  702
  703
  704
  705
  706
  707
  708
  709
  710
  711
  712
  713
  714
  715
  716
  717
  718
  719
  720
  721
  722
  723
  724
  725
  726
  727
  728
  729
  730
  731
  732
  733
  734
  735
  736
  737
  738
  739
  740
  741
  742
  743
  744
  745
  746
  747
  748
  749
  750
  751
  752
  753
  754
  755
  756
  757
  758
  759
  760
  761
  762
  763
  764
  765
  766
  767
  768
  769
  770
  771
  772
  773
  774
  775
  776
  777
  778
  779
  780
  781
  782
  783
  784
  785
  786
  787
  788
  789
  790
  791
  792
  793
  794
  795
  796
  797
  798
  799
  800
  801
  802
  803
  804
  805
  806
  807
  808
  809
  810
  811
  812
  813
  814
  815
  816
  817
  818
  819
  820
  821
  822
  823
  824
  825
  826
  827
  828
  829
  830
  831
  832
  833
  834
  835
  836
  837
  838
  839
  840
  841
  842
  843
  844
  845
  846
  847
  848
  849
  850
  851
  852
  853
  854
  855
  856
  857
  858
  859
  860
  861
  862
  863
  864
  865
  866
  867
  868
  869
  870
  871
  872
  873
  874
  875
  876
  877
  878
  879
  880
  881
  882
  883
  884
  885
  886
  887
  888
  889
  890
  891
  892
  893
  894
  895
  896
  897
  898
  899
  900
  901
  902
  903
  904
  905
  906
  907
  908
  909
  910
  911
  912
  913
  914
  915
  916
  917
  918
  919
  920
  921
  922
  923
  924
  925
  926
  927
  928
  929
  930
  931
  932
  933
  934
  935
  936
  937
  938
  939
  940
  941
  942
  943
  944
  945
  946
  947
  948
  949
  950
  951
  952
  953
  954
  955
  956
  957
  958
  959
  960
  961
  962
  963
  964
  965
  966
  967
  968
  969
  970
  971
  972
  973
  974
  975
  976
  977
  978
  979
  980
  981
  982
  983
  984
  985
  986
  987
  988
  989
  990
  991
  992
  993
  994
  995
  996
  997
  998
  999
 1000
 1001
 1002
 1003
 1004
 1005
 1006
 1007
 1008
 1009
 1010
 1011
 1012
 1013
 1014
 1015
 1016
 1017
 1018
 1019
 1020
 1021
 1022
 1023
 1024
 1025
 1026
 1027
 1028
 1029
 1030
 1031
 1032
 1033
 1034
 1035
 1036
 1037
 1038
 1039
 1040
 1041
 1042
 1043
 1044
 1045
 1046
 1047
 1048
 1049
 1050
 1051
 1052
 1053
 1054
 1055
 1056
 1057
 1058
 1059
 1060
 1061
 1062
 1063
 1064
 1065
 1066
 1067
 1068
 1069
 1070
 1071
 1072
 1073
 1074
 1075
 1076
 1077
 1078
 1079
 1080
 1081
 1082
 1083
 1084
 1085
 1086
 1087
 1088
 1089
 1090
 1091
 1092
 1093
 1094
 1095
 1096
 1097
 1098
 1099
 1100
 1101
 1102
 1103
 1104
 1105
 1106
 1107
 1108
 1109
 1110
 1111
 1112
 1113
 1114
 1115
 1116
 1117
 1118
 1119
 1120
 1121
 1122
 1123
 1124
 1125
 1126
 1127
 1128
 1129
 1130
 1131
 1132
 1133
 1134
 1135
 1136
 1137
 1138
 1139
 1140
 1141
 1142
 1143
 1144
 1145
 1146
 1147
 1148
 1149
 1150
 1151
 1152
 1153
 1154
 1155
 1156
 1157
 1158
 1159
 1160
 1161
 1162
 1163
 1164
 1165
 1166
 1167
 1168
 1169
 1170
 1171
 1172
 1173
 1174
 1175
 1176
 1177
 1178
 1179
 1180
 1181
 1182
 1183
 1184
 1185
 1186
 1187
 1188
 1189
 1190
 1191
 1192
 1193
 1194
 1195
 1196
 1197
 1198
 1199
 1200
 1201
 1202
 1203
 1204
 1205
 1206
 1207
 1208
 1209
 1210
 1211
 1212
 1213
 1214
 1215
 1216
 1217
 1218
 1219
 1220
 1221
 1222
 1223
 1224
 1225
 1226
 1227
 1228
 1229
 1230
 1231
 1232
 1233
 1234
 1235
 1236
 1237
 1238
 1239
 1240
 1241
 1242
 1243
 1244
 1245
 1246
 1247
 1248
 1249
 1250
 1251
 1252
 1253
 1254
 1255
 1256
 1257
 1258
 1259
 1260
 1261
 1262
 1263
 1264
 1265
 1266
 1267
 1268
 1269
 1270
 1271
 1272
 1273
 1274
 1275
 1276
 1277
 1278
 1279
 1280
 1281
 1282
 1283
 1284
 1285
 1286
 1287
 1288
 1289
 1290
 1291
 1292
 1293
 1294
 1295
 1296
 1297
 1298
 1299
 1300
 1301
 1302
 1303
 1304
 1305
 1306
 1307
 1308
 1309
 1310
 1311
 1312
 1313
 1314
 1315
 1316
 1317
 1318
 1319
 1320
 1321
 1322
 1323
 1324
 1325
 1326
 1327
 1328
 1329
 1330
 1331
 1332
 1333
 1334
 1335
 1336
 1337
 1338
 1339
 1340
 1341
 1342
 1343
 1344
 1345
 1346
 1347
 1348
 1349
 1350
 1351
 1352
 1353
 1354
 1355
 1356
 1357
 1358
 1359
 1360
 1361
 1362
 1363
 1364
 1365
 1366
 1367
 1368
 1369
 1370
 1371
 1372
 1373
 1374
 1375
 1376
 1377
 1378
 1379
 1380
 1381
 1382
 1383
 1384
 1385
 1386
 1387
 1388
 1389
 1390
 1391
 1392
 1393
 1394
 1395
 1396
 1397
 1398
 1399
 1400
 1401
 1402
 1403
 1404
 1405
 1406
 1407
 1408
 1409
 1410
 1411
 1412
 1413
 1414
 1415
 1416
 1417
 1418
 1419
 1420
 1421
 1422
 1423
 1424
 1425
 1426
 1427
 1428
 1429
 1430
 1431
 1432
 1433
 1434
 1435
 1436
 1437
 1438
 1439
 1440
 1441
 1442
 1443
 1444
 1445
 1446
 1447
 1448
 1449
 1450
 1451
 1452
 1453
 1454
 1455
 1456
 1457
 1458
 1459
 1460
 1461
 1462
 1463
 1464
 1465
 1466
 1467
 1468
 1469
 1470
 1471
 1472
 1473
 1474
 1475
 1476
 1477
 1478
 1479
 1480
 1481
 1482
 1483
 1484
 1485
 1486
 1487
 1488
 1489
 1490
 1491
 1492
 1493
 1494
 1495
 1496
 1497
 1498
 1499
 1500
 1501
 1502
 1503
 1504
 1505
 1506
 1507
 1508
 1509
 1510
 1511
 1512
 1513
 1514
 1515
 1516
 1517
 1518
 1519
 1520
 1521
 1522
 1523
 1524
 1525
 1526
 1527
 1528
 1529
 1530
 1531
 1532
 1533
 1534
 1535
 1536
 1537
 1538
 1539
 1540
 1541
 1542
 1543
 1544
 1545
 1546
 1547
 1548
 1549
 1550
 1551
 1552
 1553
 1554
 1555
 1556
 1557
 1558
 1559
 1560
 1561
 1562
 1563
 1564
 1565
 1566
 1567
 1568
 1569
 1570
 1571
 1572
 1573
 1574
 1575
 1576
 1577
 1578
 1579
 1580
 1581
 1582
 1583
 1584
 1585
 1586
 1587
 1588
 1589
 1590
 1591
 1592
 1593
 1594
 1595
 1596
 1597
 1598
 1599
 1600
 1601
 1602
 1603
 1604
 1605
 1606
 1607
 1608
 1609
 1610
 1611
 1612
 1613
 1614
 1615
 1616
 1617
 1618
 1619
 1620
 1621
 1622
 1623
 1624
 1625
 1626
 1627
 1628
 1629
 1630
 1631
 1632
 1633
 1634
 1635
 1636
 1637
 1638
 1639
 1640
 1641
 1642
 1643
 1644
 1645
 1646
 1647
 1648
 1649
 1650
 1651
 1652
 1653
 1654
 1655
 1656
 1657
 1658
 1659
 1660
 1661
 1662
 1663
 1664
 1665
 1666
 1667
 1668
 1669
 1670
 1671
 1672
 1673
 1674
 1675
 1676
 1677
 1678
 1679
 1680
 1681
 1682
 1683
 1684
 1685
 1686
 1687
 1688
 1689
 1690
 1691
 1692
 1693
 1694
 1695
 1696
 1697
 1698
 1699
 1700
 1701
 1702
 1703
 1704
 1705
 1706
 1707
 1708
 1709
 1710
 1711
 1712
 1713
 1714
 1715
 1716
 1717
 1718
 1719
 1720
 1721
 1722
 1723
 1724
 1725
 1726
 1727
 1728
 1729
 1730
 1731
 1732
 1733
 1734
 1735
 1736
 1737
 1738
 1739
 1740
 1741
 1742
 1743
 1744
 1745
 1746
 1747
 1748
 1749
 1750
 1751
 1752
 1753
 1754
 1755
 1756
 1757
 1758
 1759
 1760
 1761
 1762
 1763
 1764
 1765
 1766
 1767
 1768
 1769
 1770
 1771
 1772
 1773
 1774
 1775
 1776
 1777
 1778
 1779
 1780
 1781
 1782
 1783
 1784
 1785
 1786
 1787
 1788
 1789
 1790
 1791
 1792
 1793
 1794
 1795
 1796
 1797
 1798
 1799
 1800
 1801
 1802
 1803
 1804
 1805
 1806
 1807
 1808
 1809
 1810
 1811
 1812
 1813
 1814
 1815
 1816
 1817
 1818
 1819
 1820
 1821
 1822
 1823
 1824
 1825
 1826
 1827
 1828
 1829
 1830
 1831
 1832
 1833
 1834
 1835
 1836
 1837
 1838
 1839
 1840
 1841
 1842
 1843
 1844
 1845
 1846
 1847
 1848
 1849
 1850
 1851
 1852
 1853
 1854
 1855
 1856
 1857
 1858
 1859
 1860
 1861
 1862
 1863
 1864
 1865
 1866
 1867
 1868
 1869
 1870
 1871
 1872
 1873
 1874
 1875
 1876
 1877
 1878
 1879
 1880
 1881
 1882
 1883
 1884
 1885
 1886
 1887
 1888
 1889
 1890
 1891
 1892
 1893
 1894
 1895
 1896
 1897
 1898
 1899
 1900
 1901
 1902
 1903
 1904
 1905
 1906
 1907
 1908
 1909
 1910
 1911
 1912
 1913
 1914
 1915
 1916
 1917
 1918
 1919
 1920
 1921
 1922
 1923
 1924
 1925
 1926
 1927
 1928
 1929
 1930
 1931
 1932
 1933
 1934
 1935
 1936
 1937
 1938
 1939
 1940
 1941
 1942
 1943
 1944
 1945
 1946
 1947
 1948
 1949
 1950
 1951
 1952
 1953
 1954
 1955
 1956
 1957
 1958
 1959
 1960
 1961
 1962
 1963
 1964
 1965
 1966
 1967
 1968
 1969
 1970
 1971
 1972
 1973
 1974
 1975
 1976
 1977
 1978
 1979
 1980
 1981
 1982
 1983
 1984
 1985
 1986
 1987
 1988
 1989
 1990
 1991
 1992
 1993
 1994
 1995
 1996
 1997
 1998
 1999
 2000
 2001
 2002
 2003
 2004
 2005
 2006
 2007
 2008
 2009
 2010
 2011
 2012
 2013
 2014
 2015
 2016
 2017
 2018
 2019
 2020
 2021
 2022
 2023
 2024
 2025
 2026
 2027
 2028
 2029
 2030
 2031
 2032
 2033
 2034
 2035
 2036
 2037
 2038
 2039
 2040
 2041
 2042
 2043
 2044
 2045
 2046
 2047
 2048
 2049
 2050
 2051
 2052
 2053
 2054
 2055
 2056
 2057
 2058
 2059
 2060
 2061
 2062
 2063
 2064
 2065
 2066
 2067
 2068
 2069
 2070
 2071
 2072
 2073
 2074
 2075
 2076
 2077
 2078
 2079
 2080
 2081
 2082
 2083
 2084
 2085
 2086
 2087
 2088
 2089
 2090
 2091
 2092
 2093
 2094
 2095
 2096
 2097
 2098
 2099
 2100
 2101
 2102
 2103
 2104
 2105
 2106
 2107
 2108
 2109
 2110
 2111
 2112
 2113
 2114
 2115
 2116
 2117
 2118
 2119
 2120
 2121
 2122
 2123
 2124
 2125
 2126
 2127
 2128
 2129
 2130
 2131
 2132
 2133
 2134
 2135
 2136
 2137
 2138
 2139
 2140
 2141
 2142
 2143
 2144
 2145
 2146
 2147
 2148
 2149
 2150
 2151
 2152
 2153
 2154
 2155
 2156
 2157
 2158
 2159
 2160
 2161
 2162
 2163
 2164
 2165
 2166
 2167
 2168
 2169
 2170
 2171
 2172
 2173
 2174
 2175
 2176
 2177
 2178
 2179
 2180
 2181
 2182
 2183
 2184
 2185
 2186
 2187
 2188
 2189
 2190
 2191
 2192
 2193
 2194
 2195
 2196
 2197
 2198
 2199
 2200
 2201
 2202
 2203
 2204
 2205
 2206
 2207
 2208
 2209
 2210
 2211
 2212
 2213
 2214
 2215
 2216
 2217
 2218
 2219
 2220
 2221
 2222
 2223
 2224
 2225
 2226
 2227
 2228
 2229
 2230
 2231
 2232
 2233
 2234
 2235
 2236
 2237
 2238
 2239
 2240
 2241
 2242
 2243
 2244
 2245
 2246
 2247
 2248
 2249
 2250
 2251
 2252
 2253
 2254
 2255
 2256
 2257
 2258
 2259
 2260
 2261
 2262
 2263
 2264
 2265
 2266
 2267
 2268
 2269
 2270
 2271
 2272
 2273
 2274
 2275
 2276
 2277
 2278
 2279
 2280
 2281
 2282
 2283
 2284
 2285
 2286
 2287
 2288
 2289
 2290
 2291
 2292
 2293
 2294
 2295
 2296
 2297
 2298
 2299
 2300
 2301
 2302
 2303
 2304
 2305
 2306
 2307
 2308
 2309
 2310
 2311
 2312
 2313
 2314
 2315
 2316
 2317
 2318
 2319
 2320
 2321
 2322
 2323
 2324
 2325
 2326
 2327
 2328
 2329
 2330
 2331
 2332
 2333
 2334
 2335
 2336
 2337
 2338
 2339
 2340
 2341
 2342
 2343
 2344
 2345
 2346
 2347
 2348
 2349
 2350
 2351
 2352
 2353
 2354
 2355
 2356
 2357
 2358
 2359
 2360
 2361
 2362
 2363
 2364
 2365
 2366
 2367
 2368
 2369
 2370
 2371
 2372
 2373
 2374
 2375
 2376
 2377
 2378
 2379
 2380
 2381
 2382
 2383
 2384
 2385
 2386
 2387
 2388
 2389
 2390
 2391
 2392
 2393
 2394
 2395
 2396
 2397
 2398
 2399
 2400
 2401
 2402
 2403
 2404
 2405
 2406
 2407
 2408
 2409
 2410
 2411
 2412
 2413
 2414
 2415
 2416
 2417
 2418
 2419
 2420
 2421
 2422
 2423
 2424
 2425
 2426
 2427
 2428
 2429
 2430
 2431
 2432
 2433
 2434
 2435
 2436
 2437
 2438
 2439
 2440
 2441
 2442
 2443
 2444
 2445
 2446
 2447
 2448
 2449
 2450
 2451
 2452
 2453
 2454
 2455
 2456
 2457
 2458
 2459
 2460
 2461
 2462
 2463
 2464
 2465
 2466
 2467
 2468
 2469
 2470
 2471
 2472
 2473
 2474
 2475
 2476
 2477
 2478
 2479
 2480
 2481
 2482
 2483
 2484
 2485
 2486
 2487
 2488
 2489
 2490
 2491
 2492
 2493
 2494
 2495
 2496
 2497
 2498
 2499
 2500
 2501
 2502
 2503
 2504
 2505
 2506
 2507
 2508
 2509
 2510
 2511
 2512
 2513
 2514
 2515
 2516
 2517
 2518
 2519
 2520
 2521
 2522
 2523
 2524
 2525
 2526
 2527
 2528
 2529
 2530
 2531
 2532
 2533
 2534
 2535
 2536
 2537
 2538
 2539
 2540
 2541
 2542
 2543
 2544
 2545
 2546
 2547
 2548
 2549
 2550
 2551
 2552
 2553
 2554
 2555
 2556
 2557
 2558
 2559
 2560
 2561
 2562
 2563
 2564
 2565
 2566
 2567
 2568
 2569
 2570
 2571
 2572
 2573
 2574
 2575
 2576
 2577
 2578
 2579
 2580
 2581
 2582
 2583
 2584
 2585
 2586
 2587
 2588
 2589
 2590
 2591
 2592
 2593
 2594
 2595
 2596
 2597
 2598
 2599
 2600
 2601
 2602
 2603
 2604
 2605
 2606
 2607
 2608
 2609
 2610
 2611
 2612
 2613
 2614
 2615
 2616
 2617
 2618
 2619
 2620
 2621
 2622
 2623
 2624
 2625
 2626
 2627
 2628
 2629
 2630
 2631
 2632
 2633
 2634
 2635
 2636
 2637
 2638
 2639
 2640
 2641
 2642
 2643
 2644
 2645
 2646
 2647
 2648
 2649
 2650
 2651
 2652
 2653
 2654
 2655
 2656
 2657
 2658
 2659
 2660
 2661
 2662
 2663
 2664
 2665
 2666
 2667
 2668
 2669
 2670
 2671
 2672
 2673
 2674
 2675
 2676
 2677
 2678
 2679
 2680
 2681
 2682
 2683
 2684
 2685
 2686
 2687
 2688
 2689
 2690
 2691
 2692
 2693
 2694
 2695
 2696
 2697
 2698
 2699
 2700
 2701
 2702
 2703
 2704
 2705
 2706
 2707
 2708
 2709
 2710
 2711
 2712
 2713
 2714
 2715
 2716
 2717
 2718
 2719
 2720
 2721
 2722
 2723
 2724
 2725
 2726
 2727
 2728
 2729
 2730
 2731
 2732
 2733
 2734
 2735
 2736
 2737
 2738
 2739
 2740
 2741
 2742
 2743
 2744
 2745
 2746
 2747
 2748
 2749
 2750
 2751
 2752
 2753
 2754
 2755
 2756
 2757
 2758
 2759
 2760
 2761
 2762
 2763
 2764
 2765
 2766
 2767
 2768
 2769
 2770
 2771
 2772
 2773
 2774
 2775
 2776
 2777
 2778
 2779
 2780
 2781
 2782
 2783
 2784
 2785
 2786
 2787
 2788
 2789
 2790
 2791
 2792
 2793
 2794
 2795
 2796
 2797
 2798
 2799
 2800
 2801
 2802
 2803
 2804
 2805
 2806
 2807
 2808
 2809
 2810
 2811
 2812
 2813
 2814
 2815
 2816
 2817
 2818
 2819
 2820
 2821
 2822
 2823
 2824
 2825
 2826
 2827
 2828
 2829
 2830
 2831
 2832
 2833
 2834
 2835
 2836
 2837
 2838
 2839
 2840
 2841
 2842
 2843
 2844
 2845
 2846
 2847
 2848
 2849
 2850
 2851
 2852
 2853
 2854
 2855
 2856
 2857
 2858
 2859
 2860
 2861
 2862
 2863
 2864
 2865
 2866
 2867
 2868
 2869
 2870
 2871
 2872
 2873
 2874
 2875
 2876
 2877
 2878
 2879
 2880
 2881
 2882
 2883
 2884
 2885
 2886
 2887
 2888
 2889
 2890
 2891
 2892
 2893
 2894
 2895
 2896
 2897
 2898
 2899
 2900
 2901
 2902
 2903
 2904
 2905
 2906
 2907
 2908
 2909
 2910
 2911
 2912
 2913
 2914
 2915
 2916
 2917
 2918
 2919
 2920
 2921
 2922
 2923
 2924
 2925
 2926
 2927
 2928
 2929
 2930
 2931
 2932
 2933
 2934
 2935
 2936
 2937
 2938
 2939
 2940
 2941
 2942
 2943
 2944
 2945
 2946
 2947
 2948
 2949
 2950
 2951
 2952
 2953
 2954
 2955
 2956
 2957
 2958
 2959
 2960
 2961
 2962
 2963
 2964
 2965
 2966
 2967
 2968
 2969
 2970
 2971
 2972
 2973
 2974
 2975
 2976
 2977
 2978
 2979
 2980
 2981
 2982
 2983
 2984
 2985
 2986
 2987
 2988
 2989
 2990
 2991
 2992
 2993
 2994
 2995
 2996
 2997
 2998
 2999
 3000
 3001
 3002
 3003
 3004
 3005
 3006
 3007
 3008
 3009
 3010
 3011
 3012
 3013
 3014
 3015
 3016
 3017
 3018
 3019
 3020
 3021
 3022
 3023
 3024
 3025
 3026
 3027
 3028
 3029
 3030
 3031
 3032
 3033
 3034
 3035
 3036
 3037
 3038
 3039
 3040
 3041
 3042
 3043
 3044
 3045
 3046
 3047
 3048
 3049
 3050
 3051
 3052
 3053
 3054
 3055
 3056
 3057
 3058
 3059
 3060
 3061
 3062
 3063
 3064
 3065
 3066
 3067
 3068
 3069
 3070
 3071
 3072
 3073
 3074
 3075
 3076
 3077
 3078
 3079
 3080
 3081
 3082
 3083
 3084
 3085
 3086
 3087
 3088
 3089
 3090
 3091
 3092
 3093
 3094
 3095
 3096
 3097
 3098
 3099
 3100
 3101
 3102
 3103
 3104
 3105
 3106
 3107
 3108
 3109
 3110
 3111
 3112
 3113
 3114
 3115
 3116
 3117
 3118
 3119
 3120
 3121
 3122
 3123
 3124
 3125
 3126
 3127
 3128
 3129
 3130
 3131
 3132
 3133
 3134
 3135
 3136
 3137
 3138
 3139
 3140
 3141
 3142
 3143
 3144
 3145
 3146
 3147
 3148
 3149
 3150
 3151
 3152
 3153
 3154
 3155
 3156
 3157
 3158
 3159
 3160
 3161
 3162
 3163
 3164
 3165
 3166
 3167
 3168
 3169
 3170
 3171
 3172
 3173
 3174
 3175
 3176
 3177
 3178
 3179
 3180
 3181
 3182
 3183
 3184
 3185
 3186
 3187
 3188
 3189
 3190
 3191
 3192
 3193
 3194
 3195
 3196
 3197
 3198
 3199
 3200
 3201
 3202
 3203
 3204
 3205
 3206
 3207
 3208
 3209
 3210
 3211
 3212
 3213
 3214
 3215
 3216
 3217
 3218
 3219
 3220
 3221
 3222
 3223
 3224
 3225
 3226
 3227
 3228
 3229
 3230
 3231
 3232
 3233
 3234
 3235
 3236
 3237
 3238
 3239
 3240
 3241
 3242
 3243
 3244
 3245
 3246
 3247
 3248
 3249
 3250
 3251
 3252
 3253
 3254
 3255
 3256
 3257
 3258
 3259
 3260
 3261
 3262
 3263
 3264
 3265
 3266
 3267
 3268
 3269
 3270
 3271
 3272
 3273
 3274
 3275
 3276
 3277
 3278
 3279
 3280
 3281
 3282
 3283
 3284
 3285
 3286
 3287
 3288
 3289
 3290
 3291
 3292
 3293
 3294
 3295
 3296
 3297
 3298
 3299
 3300
 3301
 3302
 3303
 3304
 3305
 3306
 3307
 3308
 3309
 3310
 3311
 3312
 3313
 3314
 3315
 3316
 3317
 3318
 3319
 3320
 3321
 3322
 3323
 3324
 3325
 3326
 3327
 3328
 3329
 3330
 3331
 3332
 3333
 3334
 3335
 3336
 3337
 3338
 3339
 3340
 3341
 3342
 3343
 3344
 3345
 3346
 3347
 3348
 3349
 3350
 3351
 3352
 3353
 3354
 3355
 3356
 3357
 3358
 3359
 3360
 3361
 3362
 3363
 3364
 3365
 3366
 3367
 3368
 3369
 3370
 3371
 3372
 3373
 3374
 3375
 3376
 3377
 3378
 3379
 3380
 3381
 3382
 3383
 3384
 3385
 3386
 3387
 3388
 3389
 3390
 3391
 3392
 3393
 3394
 3395
 3396
 3397
 3398
 3399
 3400
 3401
 3402
 3403
 3404
 3405
 3406
 3407
 3408
 3409
 3410
 3411
 3412
 3413
 3414
 3415
 3416
 3417
 3418
 3419
 3420
 3421
 3422
 3423
 3424
 3425
 3426
 3427
 3428
 3429
 3430
 3431
 3432
 3433
 3434
 3435
 3436
 3437
 3438
 3439
 3440
 3441
 3442
 3443
 3444
 3445
 3446
 3447
 3448
 3449
 3450
 3451
 3452
 3453
 3454
 3455
 3456
 3457
 3458
 3459
 3460
 3461
 3462
 3463
 3464
 3465
 3466
 3467
 3468
 3469
 3470
 3471
 3472
 3473
 3474
 3475
 3476
 3477
 3478
 3479
 3480
 3481
 3482
 3483
 3484
 3485
 3486
 3487
 3488
 3489
 3490
 3491
 3492
 3493
 3494
 3495
 3496
 3497
 3498
 3499
 3500
 3501
 3502
 3503
 3504
 3505
 3506
 3507
 3508
 3509
 3510
 3511
 3512
 3513
 3514
 3515
 3516
 3517
 3518
 3519
 3520
 3521
 3522
 3523
 3524
 3525
 3526
 3527
 3528
 3529
 3530
 3531
 3532
 3533
 3534
 3535
 3536
 3537
 3538
 3539
 3540
 3541
 3542
 3543
 3544
 3545
 3546
 3547
 3548
 3549
 3550
 3551
 3552
 3553
 3554
 3555
 3556
 3557
 3558
 3559
 3560
 3561
 3562
 3563
 3564
 3565
 3566
 3567
 3568
 3569
 3570
 3571
 3572
 3573
 3574
 3575
 3576
 3577
 3578
 3579
 3580
 3581
 3582
 3583
 3584
 3585
 3586
 3587
 3588
 3589
 3590
 3591
 3592
 3593
 3594
 3595
 3596
 3597
 3598
 3599
 3600
 3601
 3602
 3603
 3604
 3605
 3606
 3607
 3608
 3609
 3610
 3611
 3612
 3613
 3614
 3615
 3616
 3617
 3618
 3619
 3620
 3621
 3622
 3623
 3624
 3625
 3626
 3627
 3628
 3629
 3630
 3631
 3632
 3633
 3634
 3635
 3636
 3637
 3638
 3639
 3640
 3641
 3642
 3643
 3644
 3645
 3646
 3647
 3648
 3649
 3650
 3651
 3652
 3653
 3654
 3655
 3656
 3657
 3658
 3659
 3660
 3661
 3662
 3663
 3664
 3665
 3666
 3667
 3668
 3669
 3670
 3671
 3672
 3673
 3674
 3675
 3676
 3677
 3678
 3679
 3680
 3681
 3682
 3683
 3684
 3685
 3686
 3687
 3688
 3689
 3690
 3691
 3692
 3693
 3694
 3695
 3696
 3697
 3698
 3699
 3700
 3701
 3702
 3703
 3704
 3705
 3706
 3707
 3708
 3709
 3710
 3711
 3712
 3713
 3714
 3715
 3716
 3717
 3718
 3719
 3720
 3721
 3722
 3723
 3724
 3725
 3726
 3727
 3728
 3729
 3730
 3731
 3732
 3733
 3734
 3735
 3736
 3737
 3738
 3739
 3740
 3741
 3742
 3743
 3744
 3745
 3746
 3747
 3748
 3749
 3750
 3751
 3752
 3753
 3754
 3755
 3756
 3757
 3758
 3759
 3760
 3761
 3762
 3763
 3764
 3765
 3766
 3767
 3768
 3769
 3770
 3771
 3772
 3773
 3774
 3775
 3776
 3777
 3778
 3779
 3780
 3781
 3782
 3783
 3784
 3785
 3786
 3787
 3788
 3789
 3790
 3791
 3792
 3793
 3794
 3795
 3796
 3797
 3798
 3799
 3800
 3801
 3802
 3803
 3804
 3805
 3806
 3807
 3808
 3809
 3810
 3811
 3812
 3813
 3814
 3815
 3816
 3817
 3818
 3819
 3820
 3821
 3822
 3823
 3824
 3825
 3826
 3827
 3828
 3829
 3830
 3831
 3832
 3833
 3834
 3835
 3836
 3837
 3838
 3839
 3840
 3841
 3842
 3843
 3844
 3845
 3846
 3847
 3848
 3849
 3850
 3851
 3852
 3853
 3854
 3855
 3856
 3857
 3858
 3859
 3860
 3861
 3862
 3863
 3864
 3865
 3866
 3867
 3868
 3869
 3870
 3871
 3872
 3873
 3874
 3875
 3876
 3877
 3878
 3879
 3880
 3881
 3882
 3883
 3884
 3885
 3886
 3887
 3888
 3889
 3890
 3891
 3892
 3893
 3894
 3895
 3896
 3897
 3898
 3899
 3900
 3901
 3902
 3903
 3904
 3905
 3906
 3907
 3908
 3909
 3910
 3911
 3912
 3913
 3914
 3915
 3916
 3917
 3918
 3919
 3920
 3921
 3922
 3923
 3924
 3925
 3926
 3927
 3928
 3929
 3930
 3931
 3932
 3933
 3934
 3935
 3936
 3937
 3938
 3939
 3940
 3941
 3942
 3943
 3944
 3945
 3946
 3947
 3948
 3949
 3950
 3951
 3952
 3953
 3954
 3955
 3956
 3957
 3958
 3959
 3960
 3961
 3962
 3963
 3964
 3965
 3966
 3967
 3968
 3969
 3970
 3971
 3972
 3973
 3974
 3975
 3976
 3977
 3978
 3979
 3980
 3981
 3982
 3983
 3984
 3985
 3986
 3987
 3988
 3989
 3990
 3991
 3992
 3993
 3994
 3995
 3996
 3997
 3998
 3999
 4000
 4001
 4002
 4003
 4004
 4005
 4006
 4007
 4008
 4009
 4010
 4011
 4012
 4013
 4014
 4015
 4016
 4017
 4018
 4019
 4020
 4021
 4022
 4023
 4024
 4025
 4026
 4027
 4028
 4029
 4030
 4031
 4032
 4033
 4034
 4035
 4036
 4037
 4038
 4039
 4040
 4041
 4042
 4043
 4044
 4045
 4046
 4047
 4048
 4049
 4050
 4051
 4052
 4053
 4054
 4055
 4056
 4057
 4058
 4059
 4060
 4061
 4062
 4063
 4064
 4065
 4066
 4067
 4068
 4069
 4070
 4071
 4072
 4073
 4074
 4075
 4076
 4077
 4078
 4079
 4080
 4081
 4082
 4083
 4084
 4085
 4086
 4087
 4088
 4089
 4090
 4091
 4092
 4093
 4094
 4095
 4096
 4097
 4098
 4099
 4100
 4101
 4102
 4103
 4104
 4105
 4106
 4107
 4108
 4109
 4110
 4111
 4112
 4113
 4114
 4115
 4116
 4117
 4118
 4119
 4120
 4121
 4122
 4123
 4124
 4125
 4126
 4127
 4128
 4129
 4130
 4131
 4132
 4133
 4134
 4135
 4136
 4137
 4138
 4139
 4140
 4141
 4142
 4143
 4144
 4145
 4146
 4147
 4148
 4149
 4150
 4151
 4152
 4153
 4154
 4155
 4156
 4157
 4158
 4159
 4160
 4161
 4162
 4163
 4164
 4165
 4166
 4167
 4168
 4169
 4170
 4171
 4172
 4173
 4174
 4175
 4176
 4177
 4178
 4179
 4180
 4181
 4182
 4183
 4184
 4185
 4186
 4187
 4188
 4189
 4190
 4191
 4192
 4193
 4194
 4195
 4196
 4197
 4198
 4199
 4200
 4201
 4202
 4203
 4204
 4205
 4206
 4207
 4208
 4209
 4210
 4211
 4212
 4213
 4214
 4215
 4216
 4217
 4218
 4219
 4220
 4221
 4222
 4223
 4224
 4225
 4226
 4227
 4228
 4229
 4230
 4231
 4232
 4233
 4234
 4235
 4236
 4237
 4238
 4239
 4240
 4241
 4242
 4243
 4244
 4245
 4246
 4247
 4248
 4249
 4250
 4251
 4252
 4253
 4254
 4255
 4256
 4257
 4258
 4259
 4260
 4261
 4262
 4263
 4264
 4265
 4266
 4267
 4268
 4269
 4270
 4271
 4272
 4273
 4274
 4275
 4276
 4277
 4278
 4279
 4280
 4281
 4282
 4283
 4284
 4285
 4286
 4287
 4288
 4289
 4290
 4291
 4292
 4293
 4294
 4295
 4296
 4297
 4298
 4299
 4300
 4301
 4302
 4303
 4304
 4305
 4306
 4307
 4308
 4309
 4310
 4311
 4312
 4313
 4314
 4315
 4316
 4317
 4318
 4319
 4320
 4321
 4322
 4323
 4324
 4325
 4326
 4327
 4328
 4329
 4330
 4331
 4332
 4333
 4334
 4335
 4336
 4337
 4338
 4339
 4340
 4341
 4342
 4343
 4344
 4345
 4346
 4347
 4348
 4349
 4350
 4351
 4352
 4353
 4354
 4355
 4356
 4357
 4358
 4359
 4360
 4361
 4362
 4363
 4364
 4365
 4366
 4367
 4368
 4369
 4370
 4371
 4372
 4373
 4374
 4375
 4376
 4377
 4378
 4379
 4380
 4381
 4382
 4383
 4384
 4385
 4386
 4387
 4388
 4389
 4390
 4391
 4392
 4393
 4394
 4395
 4396
 4397
 4398
 4399
 4400
 4401
 4402
 4403
 4404
 4405
 4406
 4407
 4408
 4409
 4410
 4411
 4412
 4413
 4414
 4415
 4416
 4417
 4418
 4419
 4420
 4421
 4422
 4423
 4424
 4425
 4426
 4427
 4428
 4429
 4430
 4431
 4432
 4433
 4434
 4435
 4436
 4437
 4438
 4439
 4440
 4441
 4442
 4443
 4444
 4445
 4446
 4447
 4448
 4449
 4450
 4451
 4452
 4453
 4454
 4455
 4456
 4457
 4458
 4459
 4460
 4461
 4462
 4463
 4464
 4465
 4466
 4467
 4468
 4469
 4470
 4471
 4472
 4473
 4474
 4475
 4476
 4477
 4478
 4479
 4480
 4481
 4482
 4483
 4484
 4485
 4486
 4487
 4488
 4489
 4490
 4491
 4492
 4493
 4494
 4495
 4496
 4497
 4498
 4499
 4500
 4501
 4502
 4503
 4504
 4505
 4506
 4507
 4508
 4509
 4510
 4511
 4512
 4513
 4514
 4515
 4516
 4517
 4518
 4519
 4520
 4521
 4522
 4523
 4524
 4525
 4526
 4527
 4528
 4529
 4530
 4531
 4532
 4533
 4534
 4535
 4536
 4537
 4538
 4539
 4540
 4541
 4542
 4543
 4544
 4545
 4546
 4547
 4548
 4549
 4550
 4551
 4552
 4553
 4554
 4555
 4556
 4557
 4558
 4559
 4560
 4561
 4562
 4563
 4564
 4565
 4566
 4567
 4568
 4569
 4570
 4571
 4572
 4573
 4574
 4575
 4576
 4577
 4578
 4579
 4580
 4581
 4582
 4583
 4584
 4585
 4586
 4587
 4588
 4589
 4590
 4591
 4592
 4593
 4594
 4595
 4596
 4597
 4598
 4599
 4600
 4601
 4602
 4603
 4604
 4605
 4606
 4607
 4608
 4609
 4610
 4611
 4612
 4613
 4614
 4615
 4616
 4617
 4618
 4619
 4620
 4621
 4622
 4623
 4624
 4625
 4626
 4627
 4628
 4629
 4630
 4631
 4632
 4633
 4634
 4635
 4636
 4637
 4638
 4639
 4640
 4641
 4642
 4643
 4644
 4645
 4646
 4647
 4648
 4649
 4650
 4651
 4652
 4653
 4654
 4655
 4656
 4657
 4658
 4659
 4660
 4661
 4662
 4663
 4664
 4665
 4666
 4667
 4668
 4669
 4670
 4671
 4672
 4673
 4674
 4675
 4676
 4677
 4678
 4679
 4680
 4681
 4682
 4683
 4684
 4685
 4686
 4687
 4688
 4689
 4690
 4691
 4692
 4693
 4694
 4695
 4696
 4697
 4698
 4699
 4700
 4701
 4702
 4703
 4704
 4705
 4706
 4707
 4708
 4709
 4710
 4711
 4712
 4713
 4714
 4715
 4716
 4717
 4718
 4719
 4720
 4721
 4722
 4723
 4724
 4725
 4726
 4727
 4728
 4729
 4730
 4731
 4732
 4733
 4734
 4735
 4736
 4737
 4738
 4739
 4740
 4741
 4742
 4743
 4744
 4745
 4746
 4747
 4748
 4749
 4750
 4751
 4752
 4753
 4754
 4755
 4756
 4757
 4758
 4759
 4760
 4761
 4762
 4763
 4764
 4765
 4766
 4767
 4768
 4769
 4770
 4771
 4772
 4773
 4774
 4775
 4776
 4777
 4778
 4779
 4780
 4781
 4782
 4783
 4784
 4785
 4786
 4787
 4788
 4789
 4790
 4791
 4792
 4793
 4794
 4795
 4796
 4797
 4798
 4799
 4800
 4801
 4802
 4803
 4804
 4805
 4806
 4807
 4808
 4809
 4810
 4811
 4812
 4813
 4814
 4815
 4816
 4817
 4818
 4819
 4820
 4821
 4822
 4823
 4824
 4825
 4826
 4827
 4828
 4829
 4830
 4831
 4832
 4833
 4834
 4835
 4836
 4837
 4838
 4839
 4840
 4841
 4842
 4843
 4844
 4845
 4846
 4847
 4848
 4849
 4850
 4851
 4852
 4853
 4854
 4855
 4856
 4857
 4858
 4859
 4860
 4861
 4862
 4863
 4864
 4865
 4866
 4867
 4868
 4869
 4870
 4871
 4872
 4873
 4874
 4875
 4876
 4877
 4878
 4879
 4880
 4881
 4882
 4883
 4884
 4885
 4886
 4887
 4888
 4889
 4890
 4891
 4892
 4893
 4894
 4895
 4896
 4897
 4898
 4899
 4900
 4901
 4902
 4903
 4904
 4905
 4906
 4907
 4908
 4909
 4910
 4911
 4912
 4913
 4914
 4915
 4916
 4917
 4918
 4919
 4920
 4921
 4922
 4923
 4924
 4925
 4926
 4927
 4928
 4929
 4930
 4931
 4932
 4933
 4934
 4935
 4936
 4937
 4938
 4939
 4940
 4941
 4942
 4943
 4944
 4945
 4946
 4947
 4948
 4949
 4950
 4951
 4952
 4953
 4954
 4955
 4956
 4957
 4958
 4959
 4960
 4961
 4962
 4963
 4964
 4965
 4966
 4967
 4968
 4969
 4970
 4971
 4972
 4973
 4974
 4975
 4976
 4977
 4978
 4979
 4980
 4981
 4982
 4983
 4984
 4985
 4986
 4987
 4988
 4989
 4990
 4991
 4992
 4993
 4994
 4995
 4996
 4997
 4998
 4999
 5000
 5001
 5002
 5003
 5004
 5005
 5006
 5007
 5008
 5009
 5010
 5011
 5012
 5013
 5014
 5015
 5016
 5017
 5018
 5019
 5020
 5021
 5022
 5023
 5024
 5025
 5026
 5027
 5028
 5029
 5030
 5031
 5032
 5033
 5034
 5035
 5036
 5037
 5038
 5039
 5040
 5041
 5042
 5043
 5044
 5045
 5046
 5047
 5048
 5049
 5050
 5051
 5052
 5053
 5054
 5055
 5056
 5057
 5058
 5059
 5060
 5061
 5062
 5063
 5064
 5065
 5066
 5067
 5068
 5069
 5070
 5071
 5072
 5073
 5074
 5075
 5076
 5077
 5078
 5079
 5080
 5081
 5082
 5083
 5084
 5085
 5086
 5087
 5088
 5089
 5090
 5091
 5092
 5093
 5094
 5095
 5096
 5097
 5098
 5099
 5100
 5101
 5102
 5103
 5104
 5105
 5106
 5107
 5108
 5109
 5110
 5111
 5112
 5113
 5114
 5115
 5116
 5117
 5118
 5119
 5120
 5121
 5122
 5123
 5124
 5125
 5126
 5127
 5128
 5129
 5130
 5131
 5132
 5133
 5134
 5135
 5136
 5137
 5138
 5139
 5140
 5141
 5142
 5143
 5144
 5145
 5146
 5147
 5148
 5149
 5150
 5151
 5152
 5153
 5154
 5155
 5156
 5157
 5158
 5159
 5160
 5161
 5162
 5163
 5164
 5165
 5166
 5167
 5168
 5169
 5170
 5171
 5172
 5173
 5174
 5175
 5176
 5177
 5178
 5179
 5180
 5181
 5182
 5183
 5184
 5185
 5186
 5187
 5188
 5189
 5190
 5191
 5192
 5193
 5194
 5195
 5196
 5197
 5198
 5199
 5200
 5201
 5202
 5203
 5204
 5205
 5206
 5207
 5208
 5209
 5210
 5211
 5212
 5213
 5214
 5215
 5216
 5217
 5218
 5219
 5220
 5221
 5222
 5223
 5224
 5225
 5226
 5227
 5228
 5229
 5230
 5231
 5232
 5233
 5234
 5235
 5236
 5237
 5238
 5239
 5240
 5241
 5242
 5243
 5244
 5245
 5246
 5247
 5248
 5249
 5250
 5251
 5252
 5253
 5254
 5255
 5256
 5257
 5258
 5259
 5260
 5261
 5262
 5263
 5264
 5265
 5266
 5267
 5268
 5269
 5270
 5271
 5272
 5273
 5274
 5275
 5276
 5277
 5278
 5279
 5280
 5281
 5282
 5283
 5284
 5285
 5286
 5287
 5288
 5289
 5290
 5291
 5292
 5293
 5294
 5295
 5296
 5297
 5298
 5299
 5300
 5301
 5302
 5303
 5304
 5305
 5306
 5307
 5308
 5309
 5310
 5311
 5312
 5313
 5314
 5315
 5316
 5317
 5318
 5319
 5320
 5321
 5322
 5323
 5324
 5325
 5326
 5327
 5328
 5329
 5330
 5331
 5332
 5333
 5334
 5335
 5336
 5337
 5338
 5339
 5340
 5341
 5342
 5343
 5344
 5345
 5346
 5347
 5348
 5349
 5350
 5351
 5352
 5353
 5354
 5355
 5356
 5357
 5358
 5359
 5360
 5361
 5362
 5363
 5364
 5365
 5366
 5367
 5368
 5369
 5370
 5371
 5372
 5373
 5374
 5375
 5376
 5377
 5378
 5379
 5380
 5381
 5382
 5383
 5384
 5385
 5386
 5387
 5388
 5389
 5390
 5391
 5392
 5393
 5394
 5395
 5396
 5397
 5398
 5399
 5400
 5401
 5402
 5403
 5404
 5405
 5406
 5407
 5408
 5409
 5410
 5411
 5412
 5413
 5414
 5415
 5416
 5417
 5418
 5419
 5420
 5421
 5422
 5423
 5424
 5425
 5426
 5427
 5428
 5429
 5430
 5431
 5432
 5433
 5434
 5435
 5436
 5437
 5438
 5439
 5440
 5441
 5442
 5443
 5444
 5445
 5446
 5447
 5448
 5449
 5450
 5451
 5452
 5453
 5454
 5455
 5456
 5457
 5458
 5459
 5460
 5461
 5462
 5463
 5464
 5465
 5466
 5467
 5468
 5469
 5470
 5471
 5472
 5473
 5474
 5475
 5476
 5477
 5478
 5479
 5480
 5481
 5482
 5483
 5484
 5485
 5486
 5487
 5488
 5489
 5490
 5491
 5492
 5493
 5494
 5495
 5496
 5497
 5498
 5499
 5500
 5501
 5502
 5503
 5504
 5505
 5506
 5507
 5508
 5509
 5510
 5511
 5512
 5513
 5514
 5515
 5516
 5517
 5518
 5519
 5520
 5521
 5522
 5523
 5524
 5525
 5526
 5527
 5528
 5529
 5530
 5531
 5532
 5533
 5534
 5535
 5536
 5537
 5538
 5539
 5540
 5541
 5542
 5543
 5544
 5545
 5546
 5547
 5548
 5549
 5550
 5551
 5552
 5553
 5554
 5555
 5556
 5557
 5558
 5559
 5560
 5561
 5562
 5563
 5564
 5565
 5566
 5567
 5568
 5569
 5570
 5571
 5572
 5573
 5574
 5575
 5576
 5577
 5578
 5579
 5580
 5581
 5582
 5583
 5584
 5585
 5586
 5587
 5588
 5589
 5590
 5591
 5592
 5593
 5594
 5595
 5596
 5597
 5598
 5599
 5600
 5601
 5602
 5603
 5604
 5605
 5606
 5607
 5608
 5609
 5610
 5611
 5612
 5613
 5614
 5615
 5616
 5617
 5618
 5619
 5620
 5621
 5622
 5623
 5624
 5625
 5626
 5627
 5628
 5629
 5630
 5631
 5632
 5633
 5634
 5635
 5636
 5637
 5638
 5639
 5640
 5641
 5642
 5643
 5644
 5645
 5646
 5647
 5648
 5649
 5650
 5651
 5652
 5653
 5654
 5655
 5656
 5657
 5658
 5659
 5660
 5661
 5662
 5663
 5664
 5665
 5666
 5667
 5668
 5669
 5670
 5671
 5672
 5673
 5674
 5675
 5676
 5677
 5678
 5679
 5680
 5681
 5682
 5683
 5684
 5685
 5686
 5687
 5688
 5689
 5690
 5691
 5692
 5693
 5694
 5695
 5696
 5697
 5698
 5699
 5700
 5701
 5702
 5703
 5704
 5705
 5706
 5707
 5708
 5709
 5710
 5711
 5712
 5713
 5714
 5715
 5716
 5717
 5718
 5719
 5720
 5721
 5722
 5723
 5724
 5725
 5726
 5727
 5728
 5729
 5730
 5731
 5732
 5733
 5734
 5735
 5736
 5737
 5738
 5739
 5740
 5741
 5742
 5743
 5744
 5745
 5746
 5747
 5748
 5749
 5750
 5751
 5752
 5753
 5754
 5755
 5756
 5757
 5758
 5759
 5760
 5761
 5762
 5763
 5764
 5765
 5766
 5767
 5768
 5769
 5770
 5771
 5772
 5773
 5774
 5775
 5776
 5777
 5778
 5779
 5780
 5781
 5782
 5783
 5784
 5785
 5786
 5787
 5788
 5789
 5790
 5791
 5792
 5793
 5794
 5795
 5796
 5797
 5798
 5799
 5800
 5801
 5802
 5803
 5804
 5805
 5806
 5807
 5808
 5809
 5810
 5811
 5812
 5813
 5814
 5815
 5816
 5817
 5818
 5819
 5820
 5821
 5822
 5823
 5824
 5825
 5826
 5827
 5828
 5829
 5830
 5831
 5832
 5833
 5834
 5835
 5836
 5837
 5838
 5839
 5840
 5841
 5842
 5843
 5844
 5845
 5846
 5847
 5848
 5849
 5850
 5851
 5852
 5853
 5854
 5855
 5856
 5857
 5858
 5859
 5860
 5861
 5862
 5863
 5864
 5865
 5866
 5867
 5868
 5869
 5870
 5871
 5872
 5873
 5874
 5875
 5876
 5877
 5878
 5879
 5880
 5881
 5882
 5883
 5884
 5885
 5886
 5887
 5888
 5889
 5890
 5891
 5892
 5893
 5894
 5895
 5896
 5897
 5898
 5899
 5900
 5901
 5902
 5903
 5904
 5905
 5906
 5907
 5908
 5909
 5910
 5911
 5912
 5913
 5914
 5915
 5916
 5917
 5918
 5919
 5920
 5921
 5922
 5923
 5924
 5925
 5926
 5927
 5928
 5929
 5930
 5931
 5932
 5933
 5934
 5935
 5936
 5937
 5938
 5939
 5940
 5941
 5942
 5943
 5944
 5945
 5946
 5947
 5948
 5949
 5950
 5951
 5952
 5953
 5954
 5955
 5956
 5957
 5958
 5959
 5960
 5961
 5962
 5963
 5964
 5965
 5966
 5967
 5968
 5969
 5970
 5971
 5972
 5973
 5974
 5975
 5976
 5977
 5978
 5979
 5980
 5981
 5982
 5983
 5984
 5985
 5986
 5987
 5988
 5989
 5990
 5991
 5992
 5993
 5994
 5995
 5996
 5997
 5998
 5999
 6000
 6001
 6002
 6003
 6004
 6005
 6006
 6007
 6008
 6009
 6010
 6011
 6012
 6013
 6014
 6015
 6016
 6017
 6018
 6019
 6020
 6021
 6022
 6023
 6024
 6025
 6026
 6027
 6028
 6029
 6030
 6031
 6032
 6033
 6034
 6035
 6036
 6037
 6038
 6039
 6040
 6041
 6042
 6043
 6044
 6045
 6046
 6047
 6048
 6049
 6050
 6051
 6052
 6053
 6054
 6055
 6056
 6057
 6058
 6059
 6060
 6061
 6062
 6063
 6064
 6065
 6066
 6067
 6068
 6069
 6070
 6071
 6072
 6073
 6074
 6075
 6076
 6077
 6078
 6079
 6080
 6081
 6082
 6083
 6084
 6085
 6086
 6087
 6088
 6089
 6090
 6091
 6092
 6093
 6094
 6095
 6096
 6097
 6098
 6099
 6100
 6101
 6102
 6103
 6104
 6105
 6106
 6107
 6108
 6109
 6110
 6111
 6112
 6113
 6114
 6115
 6116
 6117
 6118
 6119
 6120
 6121
 6122
 6123
 6124
 6125
 6126
 6127
 6128
 6129
 6130
 6131
 6132
 6133
 6134
 6135
 6136
 6137
 6138
 6139
 6140
 6141
 6142
 6143
 6144
 6145
 6146
 6147
 6148
 6149
 6150
 6151
 6152
 6153
 6154
 6155
 6156
 6157
 6158
 6159
 6160
 6161
 6162
 6163
 6164
 6165
 6166
 6167
 6168
 6169
 6170
 6171
 6172
 6173
 6174
 6175
 6176
 6177
 6178
 6179
 6180
 6181
 6182
 6183
 6184
 6185
 6186
 6187
 6188
 6189
 6190
 6191
 6192
 6193
 6194
 6195
 6196
 6197
 6198
 6199
 6200
 6201
 6202
 6203
 6204
 6205
 6206
 6207
 6208
 6209
 6210
 6211
 6212
 6213
 6214
 6215
 6216
 6217
 6218
 6219
 6220
 6221
 6222
 6223
 6224
 6225
 6226
 6227
 6228
 6229
 6230
 6231
 6232
 6233
 6234
 6235
 6236
 6237
 6238
 6239
 6240
 6241
 6242
 6243
 6244
 6245
 6246
 6247
 6248
 6249
 6250
 6251
 6252
 6253
 6254
 6255
 6256
 6257
 6258
 6259
 6260
 6261
 6262
 6263
 6264
 6265
 6266
 6267
 6268
 6269
 6270
 6271
 6272
 6273
 6274
 6275
 6276
 6277
 6278
 6279
 6280
 6281
 6282
 6283
 6284
 6285
 6286
 6287
 6288
 6289
 6290
 6291
 6292
 6293
 6294
 6295
 6296
 6297
 6298
 6299
 6300
 6301
 6302
 6303
 6304
 6305
 6306
 6307
 6308
 6309
 6310
 6311
 6312
 6313
 6314
 6315
 6316
 6317
 6318
 6319
 6320
 6321
 6322
 6323
 6324
 6325
 6326
 6327
 6328
 6329
 6330
 6331
 6332
 6333
 6334
 6335
 6336
 6337
 6338
 6339
 6340
 6341
 6342
 6343
 6344
 6345
 6346
 6347
 6348
 6349
 6350
 6351
 6352
 6353
 6354
 6355
 6356
 6357
 6358
 6359
 6360
 6361
 6362
 6363
 6364
 6365
 6366
 6367
 6368
 6369
 6370
 6371
 6372
 6373
 6374
 6375
 6376
 6377
 6378
 6379
 6380
 6381
 6382
 6383
 6384
 6385
 6386
 6387
 6388
 6389
 6390
 6391
 6392
 6393
 6394
 6395
 6396
 6397
 6398
 6399
 6400
 6401
 6402
 6403
 6404
 6405
 6406
 6407
 6408
 6409
 6410
 6411
 6412
 6413
 6414
 6415
 6416
 6417
 6418
 6419
 6420
 6421
 6422
 6423
 6424
 6425
 6426
 6427
 6428
 6429
 6430
 6431
 6432
 6433
 6434
 6435
 6436
 6437
 6438
 6439
 6440
 6441
 6442
 6443
 6444
 6445
 6446
 6447
 6448
 6449
 6450
 6451
 6452
 6453
 6454
 6455
 6456
 6457
 6458
 6459
 6460
 6461
 6462
 6463
 6464
 6465
 6466
 6467
 6468
 6469
 6470
 6471
 6472
 6473
 6474
 6475
 6476
 6477
 6478
 6479
 6480
 6481
 6482
 6483
 6484
 6485
 6486
 6487
 6488
 6489
 6490
 6491
 6492
 6493
 6494
 6495
 6496
 6497
 6498
 6499
 6500
 6501
 6502
 6503
 6504
 6505
 6506
 6507
 6508
 6509
 6510
 6511
 6512
 6513
 6514
 6515
 6516
 6517
 6518
 6519
 6520
 6521
 6522
 6523
 6524
 6525
 6526
 6527
 6528
 6529
 6530
 6531
 6532
 6533
 6534
 6535
 6536
 6537
 6538
 6539
 6540
 6541
 6542
 6543
 6544
 6545
 6546
 6547
 6548
 6549
 6550
 6551
 6552
 6553
 6554
 6555
 6556
 6557
 6558
 6559
 6560
 6561
 6562
 6563
 6564
 6565
 6566
 6567
 6568
 6569
 6570
 6571
 6572
 6573
 6574
 6575
 6576
 6577
 6578
 6579
 6580
 6581
 6582
 6583
 6584
 6585
 6586
 6587
 6588
 6589
 6590
 6591
 6592
 6593
 6594
 6595
 6596
 6597
 6598
 6599
 6600
 6601
 6602
 6603
 6604
 6605
 6606
 6607
 6608
 6609
 6610
 6611
 6612
 6613
 6614
 6615
 6616
 6617
 6618
 6619
 6620
 6621
 6622
 6623
 6624
 6625
 6626
 6627
 6628
 6629
 6630
 6631
 6632
 6633
 6634
 6635
 6636
 6637
 6638
 6639
 6640
 6641
 6642
 6643
 6644
 6645
 6646
 6647
 6648
 6649
 6650
 6651
 6652
 6653
 6654
 6655
 6656
 6657
 6658
 6659
 6660
 6661
 6662
 6663
 6664
 6665
 6666
 6667
 6668
 6669
 6670
 6671
 6672
 6673
 6674
 6675
 6676
 6677
 6678
 6679
 6680
 6681
 6682
 6683
 6684
 6685
 6686
 6687
 6688
 6689
 6690
 6691
 6692
 6693
 6694
 6695
 6696
 6697
 6698
 6699
 6700
 6701
 6702
 6703
 6704
 6705
 6706
 6707
 6708
 6709
 6710
 6711
 6712
 6713
 6714
 6715
 6716
 6717
 6718
 6719
 6720
 6721
 6722
 6723
 6724
 6725
 6726
 6727
 6728
 6729
 6730
 6731
 6732
 6733
 6734
 6735
 6736
 6737
 6738
 6739
 6740
 6741
 6742
 6743
 6744
 6745
 6746
 6747
 6748
 6749
 6750
 6751
 6752
 6753
 6754
 6755
 6756
 6757
 6758
 6759
 6760
 6761
 6762
 6763
 6764
 6765
 6766
 6767
 6768
 6769
 6770
 6771
 6772
 6773
 6774
 6775
 6776
 6777
 6778
 6779
 6780
 6781
 6782
 6783
 6784
 6785
 6786
 6787
 6788
 6789
 6790
 6791
 6792
 6793
 6794
 6795
 6796
 6797
 6798
 6799
 6800
 6801
 6802
 6803
 6804
 6805
 6806
 6807
 6808
 6809
 6810
 6811
 6812
 6813
 6814
 6815
 6816
 6817
 6818
 6819
 6820
 6821
 6822
 6823
 6824
 6825
 6826
 6827
 6828
 6829
 6830
 6831
 6832
 6833
 6834
 6835
 6836
 6837
 6838
 6839
 6840
 6841
 6842
 6843
 6844
 6845
 6846
 6847
 6848
 6849
 6850
 6851
 6852
 6853
 6854
 6855
 6856
 6857
 6858
 6859
 6860
 6861
 6862
 6863
 6864
 6865
 6866
 6867
 6868
 6869
 6870
 6871
 6872
 6873
 6874
 6875
 6876
 6877
 6878
 6879
 6880
 6881
 6882
 6883
 6884
 6885
 6886
 6887
 6888
 6889
 6890
 6891
 6892
 6893
 6894
 6895
 6896
 6897
 6898
 6899
 6900
 6901
 6902
 6903
 6904
 6905
 6906
 6907
 6908
 6909
 6910
 6911
 6912
 6913
 6914
 6915
 6916
 6917
 6918
 6919
 6920
 6921
 6922
 6923
 6924
 6925
 6926
 6927
 6928
 6929
 6930
 6931
 6932
 6933
 6934
 6935
 6936
 6937
 6938
 6939
 6940
 6941
 6942
 6943
 6944
 6945
 6946
 6947
 6948
 6949
 6950
 6951
 6952
 6953
 6954
 6955
 6956
 6957
 6958
 6959
 6960
 6961
 6962
 6963
 6964
 6965
 6966
 6967
 6968
 6969
 6970
 6971
 6972
 6973
 6974
 6975
 6976
 6977
 6978
 6979
 6980
 6981
 6982
 6983
 6984
 6985
 6986
 6987
 6988
 6989
 6990
 6991
 6992
 6993
 6994
 6995
 6996
 6997
 6998
 6999
 7000
 7001
 7002
 7003
 7004
 7005
 7006
 7007
 7008
 7009
 7010
 7011
 7012
 7013
 7014
 7015
 7016
 7017
 7018
 7019
 7020
 7021
 7022
 7023
 7024
 7025
 7026
 7027
 7028
 7029
 7030
 7031
 7032
 7033
 7034
 7035
 7036
 7037
 7038
 7039
 7040
 7041
 7042
 7043
 7044
 7045
 7046
 7047
 7048
 7049
 7050
 7051
 7052
 7053
 7054
 7055
 7056
 7057
 7058
 7059
 7060
 7061
 7062
 7063
 7064
 7065
 7066
 7067
 7068
 7069
 7070
 7071
 7072
 7073
 7074
 7075
 7076
 7077
 7078
 7079
 7080
 7081
 7082
 7083
 7084
 7085
 7086
 7087
 7088
 7089
 7090
 7091
 7092
 7093
 7094
 7095
 7096
 7097
 7098
 7099
 7100
 7101
 7102
 7103
 7104
 7105
 7106
 7107
 7108
 7109
 7110
 7111
 7112
 7113
 7114
 7115
 7116
 7117
 7118
 7119
 7120
 7121
 7122
 7123
 7124
 7125
 7126
 7127
 7128
 7129
 7130
 7131
 7132
 7133
 7134
 7135
 7136
 7137
 7138
 7139
 7140
 7141
 7142
 7143
 7144
 7145
 7146
 7147
 7148
 7149
 7150
 7151
 7152
 7153
 7154
 7155
 7156
 7157
 7158
 7159
 7160
 7161
 7162
 7163
 7164
 7165
 7166
 7167
 7168
 7169
 7170
 7171
 7172
 7173
 7174
 7175
 7176
 7177
 7178
 7179
 7180
 7181
 7182
 7183
 7184
 7185
 7186
 7187
 7188
 7189
 7190
 7191
 7192
 7193
 7194
 7195
 7196
 7197
 7198
 7199
 7200
 7201
 7202
 7203
 7204
 7205
 7206
 7207
 7208
 7209
 7210
 7211
 7212
 7213
 7214
 7215
 7216
 7217
 7218
 7219
 7220
 7221
 7222
 7223
 7224
 7225
 7226
 7227
 7228
 7229
 7230
 7231
 7232
 7233
 7234
 7235
 7236
 7237
 7238
 7239
 7240
 7241
 7242
 7243
 7244
 7245
 7246
 7247
 7248
 7249
 7250
 7251
 7252
 7253
 7254
 7255
 7256
 7257
 7258
 7259
 7260
 7261
 7262
 7263
 7264
 7265
 7266
 7267
 7268
 7269
 7270
 7271
 7272
 7273
 7274
 7275
 7276
 7277
 7278
 7279
 7280
 7281
 7282
 7283
 7284
 7285
 7286
 7287
 7288
 7289
 7290
 7291
 7292
 7293
 7294
 7295
 7296
 7297
 7298
 7299
 7300
 7301
 7302
 7303
 7304
 7305
 7306
 7307
 7308
 7309
 7310
 7311
 7312
 7313
 7314
 7315
 7316
 7317
 7318
 7319
 7320
 7321
 7322
 7323
 7324
 7325
 7326
 7327
 7328
 7329
 7330
 7331
 7332
 7333
 7334
 7335
 7336
 7337
 7338
 7339
 7340
 7341
 7342
 7343
 7344
 7345
 7346
 7347
 7348
 7349
 7350
 7351
 7352
 7353
 7354
 7355
 7356
 7357
 7358
 7359
 7360
 7361
 7362
 7363
 7364
 7365
 7366
 7367
 7368
 7369
 7370
 7371
 7372
 7373
 7374
 7375
 7376
 7377
 7378
 7379
 7380
 7381
 7382
 7383
 7384
 7385
 7386
 7387
 7388
 7389
 7390
 7391
 7392
 7393
 7394
 7395
 7396
 7397
 7398
 7399
 7400
 7401
 7402
 7403
 7404
 7405
 7406
 7407
 7408
 7409
 7410
 7411
 7412
 7413
 7414
 7415
 7416
 7417
 7418
 7419
 7420
 7421
 7422
 7423
 7424
 7425
 7426
 7427
 7428
 7429
 7430
 7431
 7432
 7433
 7434
 7435
 7436
 7437
 7438
 7439
 7440
 7441
 7442
 7443
 7444
 7445
 7446
 7447
 7448
 7449
 7450
 7451
 7452
 7453
 7454
 7455
 7456
 7457
 7458
 7459
 7460
 7461
 7462
 7463
 7464
 7465
 7466
 7467
 7468
 7469
 7470
 7471
 7472
 7473
 7474
 7475
 7476
 7477
 7478
 7479
 7480
 7481
 7482
 7483
 7484
 7485
 7486
 7487
 7488
 7489
 7490
 7491
 7492
 7493
 7494
 7495
 7496
 7497
 7498
 7499
 7500
 7501
 7502
 7503
 7504
 7505
 7506
 7507
 7508
 7509
 7510
 7511
 7512
 7513
 7514
 7515
 7516
 7517
 7518
 7519
 7520
 7521
 7522
 7523
 7524
 7525
 7526
 7527
 7528
 7529
 7530
 7531
 7532
 7533
 7534
 7535
 7536
 7537
 7538
 7539
 7540
 7541
 7542
 7543
 7544
 7545
 7546
 7547
 7548
 7549
 7550
 7551
 7552
 7553
 7554
 7555
 7556
 7557
 7558
 7559
 7560
 7561
 7562
 7563
 7564
 7565
 7566
 7567
 7568
 7569
 7570
 7571
 7572
 7573
 7574
 7575
 7576
 7577
 7578
 7579
 7580
 7581
 7582
 7583
 7584
 7585
 7586
 7587
 7588
 7589
 7590
 7591
 7592
 7593
 7594
 7595
 7596
 7597
 7598
 7599
 7600
 7601
 7602
 7603
 7604
 7605
 7606
 7607
 7608
 7609
 7610
 7611
 7612
 7613
 7614
 7615
 7616
 7617
 7618
 7619
 7620
 7621
 7622
 7623
 7624
 7625
 7626
 7627
 7628
 7629
 7630
 7631
 7632
 7633
 7634
 7635
 7636
 7637
 7638
 7639
 7640
 7641
 7642
 7643
 7644
 7645
 7646
 7647
 7648
 7649
 7650
 7651
 7652
 7653
 7654
 7655
 7656
 7657
 7658
 7659
 7660
 7661
 7662
 7663
 7664
 7665
 7666
 7667
 7668
 7669
 7670
 7671
 7672
 7673
 7674
 7675
 7676
 7677
 7678
 7679
 7680
 7681
 7682
 7683
 7684
 7685
 7686
 7687
 7688
 7689
 7690
 7691
 7692
 7693
 7694
 7695
 7696
 7697
 7698
 7699
 7700
 7701
 7702
 7703
 7704
 7705
 7706
 7707
 7708
 7709
 7710
 7711
 7712
 7713
 7714
 7715
 7716
 7717
 7718
 7719
 7720
 7721
 7722
 7723
 7724
 7725
 7726
 7727
 7728
 7729
 7730
 7731
 7732
 7733
 7734
 7735
 7736
 7737
 7738
 7739
 7740
 7741
 7742
 7743
 7744
 7745
 7746
 7747
 7748
 7749
 7750
 7751
 7752
 7753
 7754
 7755
 7756
 7757
 7758
 7759
 7760
 7761
 7762
 7763
 7764
 7765
 7766
 7767
 7768
 7769
 7770
 7771
 7772
 7773
 7774
 7775
 7776
 7777
 7778
 7779
 7780
 7781
 7782
 7783
 7784
 7785
 7786
 7787
 7788
 7789
 7790
 7791
 7792
 7793
 7794
 7795
 7796
 7797
 7798
 7799
 7800
 7801
 7802
 7803
 7804
 7805
 7806
 7807
 7808
 7809
 7810
 7811
 7812
 7813
 7814
 7815
 7816
 7817
 7818
 7819
 7820
 7821
 7822
 7823
 7824
 7825
 7826
 7827
 7828
 7829
 7830
 7831
 7832
 7833
 7834
 7835
 7836
 7837
 7838
 7839
 7840
 7841
 7842
 7843
 7844
 7845
 7846
 7847
 7848
 7849
 7850
 7851
 7852
 7853
 7854
 7855
 7856
 7857
 7858
 7859
 7860
 7861
 7862
 7863
 7864
 7865
 7866
 7867
 7868
 7869
 7870
 7871
 7872
 7873
 7874
 7875
 7876
 7877
 7878
 7879
 7880
 7881
 7882
 7883
 7884
 7885
 7886
 7887
 7888
 7889
 7890
 7891
 7892
 7893
 7894
 7895
 7896
 7897
 7898
 7899
 7900
 7901
 7902
 7903
 7904
 7905
 7906
 7907
 7908
 7909
 7910
 7911
 7912
 7913
 7914
 7915
 7916
 7917
 7918
 7919
 7920
 7921
 7922
 7923
 7924
 7925
 7926
 7927
 7928
 7929
 7930
 7931
 7932
 7933
 7934
 7935
 7936
 7937
 7938
 7939
 7940
 7941
 7942
 7943
 7944
 7945
 7946
 7947
 7948
 7949
 7950
 7951
 7952
 7953
 7954
 7955
 7956
 7957
 7958
 7959
 7960
 7961
 7962
 7963
 7964
 7965
 7966
 7967
 7968
 7969
 7970
 7971
 7972
 7973
 7974
 7975
 7976
 7977
 7978
 7979
 7980
 7981
 7982
 7983
 7984
 7985
 7986
 7987
 7988
 7989
 7990
 7991
 7992
 7993
 7994
 7995
 7996
 7997
 7998
 7999
 8000
 8001
 8002
 8003
 8004
 8005
 8006
 8007
 8008
 8009
 8010
 8011
 8012
 8013
 8014
 8015
 8016
 8017
 8018
 8019
 8020
 8021
 8022
 8023
 8024
 8025
 8026
 8027
 8028
 8029
 8030
 8031
 8032
 8033
 8034
 8035
 8036
 8037
 8038
 8039
 8040
 8041
 8042
 8043
 8044
 8045
 8046
 8047
 8048
 8049
 8050
 8051
 8052
 8053
 8054
 8055
 8056
 8057
 8058
 8059
 8060
 8061
 8062
 8063
 8064
 8065
 8066
 8067
 8068
 8069
 8070
 8071
 8072
 8073
 8074
 8075
 8076
 8077
 8078
 8079
 8080
 8081
 8082
 8083
 8084
 8085
 8086
 8087
 8088
 8089
 8090
 8091
 8092
 8093
 8094
 8095
 8096
 8097
 8098
 8099
 8100
 8101
 8102
 8103
 8104
 8105
 8106
 8107
 8108
 8109
 8110
 8111
 8112
 8113
 8114
 8115
 8116
 8117
 8118
 8119
 8120
 8121
 8122
 8123
 8124
 8125
 8126
 8127
 8128
 8129
 8130
 8131
 8132
 8133
 8134
 8135
 8136
 8137
 8138
 8139
 8140
 8141
 8142
 8143
 8144
 8145
 8146
 8147
 8148
 8149
 8150
 8151
 8152
 8153
 8154
 8155
 8156
 8157
 8158
 8159
 8160
 8161
 8162
 8163
 8164
 8165
 8166
 8167
 8168
 8169
 8170
 8171
 8172
 8173
 8174
 8175
 8176
 8177
 8178
 8179
 8180
 8181
 8182
 8183
 8184
 8185
 8186
 8187
 8188
 8189
 8190
 8191
 8192
 8193
 8194
 8195
 8196
 8197
 8198
 8199
 8200
 8201
 8202
 8203
 8204
 8205
 8206
 8207
 8208
 8209
 8210
 8211
 8212
 8213
 8214
 8215
 8216
 8217
 8218
 8219
 8220
 8221
 8222
 8223
 8224
 8225
 8226
 8227
 8228
 8229
 8230
 8231
 8232
 8233
 8234
 8235
 8236
 8237
 8238
 8239
 8240
 8241
 8242
 8243
 8244
 8245
 8246
 8247
 8248
 8249
 8250
 8251
 8252
 8253
 8254
 8255
 8256
 8257
 8258
 8259
 8260
 8261
 8262
 8263
 8264
 8265
 8266
 8267
 8268
 8269
 8270
 8271
 8272
 8273
 8274
 8275
 8276
 8277
 8278
 8279
 8280
 8281
 8282
 8283
 8284
 8285
 8286
 8287
 8288
 8289
 8290
 8291
 8292
 8293
 8294
 8295
 8296
 8297
 8298
 8299
 8300
 8301
 8302
 8303
 8304
 8305
 8306
 8307
 8308
 8309
 8310
 8311
 8312
 8313
 8314
 8315
 8316
 8317
 8318
 8319
 8320
 8321
 8322
 8323
 8324
 8325
 8326
 8327
 8328
 8329
 8330
 8331
 8332
 8333
 8334
 8335
 8336
 8337
 8338
 8339
 8340
 8341
 8342
 8343
 8344
 8345
 8346
 8347
 8348
 8349
 8350
 8351
 8352
 8353
 8354
 8355
 8356
 8357
 8358
 8359
 8360
 8361
 8362
 8363
 8364
 8365
 8366
 8367
 8368
 8369
 8370
 8371
 8372
 8373
 8374
 8375
 8376
 8377
 8378
 8379
 8380
 8381
 8382
 8383
 8384
 8385
 8386
 8387
 8388
 8389
 8390
 8391
 8392
 8393
 8394
 8395
 8396
 8397
 8398
 8399
 8400
 8401
 8402
 8403
 8404
 8405
 8406
 8407
 8408
 8409
 8410
 8411
 8412
 8413
 8414
 8415
 8416
 8417
 8418
 8419
 8420
 8421
 8422
 8423
 8424
 8425
 8426
 8427
 8428
 8429
 8430
 8431
 8432
 8433
 8434
 8435
 8436
 8437
 8438
 8439
 8440
 8441
 8442
 8443
 8444
 8445
 8446
 8447
 8448
 8449
 8450
 8451
 8452
 8453
 8454
 8455
 8456
 8457
 8458
 8459
 8460
 8461
 8462
 8463
 8464
 8465
 8466
 8467
 8468
 8469
 8470
 8471
 8472
 8473
 8474
 8475
 8476
 8477
 8478
 8479
 8480
 8481
 8482
 8483
 8484
 8485
 8486
 8487
 8488
 8489
 8490
 8491
 8492
 8493
 8494
 8495
 8496
 8497
 8498
 8499
 8500
 8501
 8502
 8503
 8504
 8505
 8506
 8507
 8508
 8509
 8510
 8511
 8512
 8513
 8514
 8515
 8516
 8517
 8518
 8519
 8520
 8521
 8522
 8523
 8524
 8525
 8526
 8527
 8528
 8529
 8530
 8531
 8532
 8533
 8534
 8535
 8536
 8537
 8538
 8539
 8540
 8541
 8542
 8543
 8544
 8545
 8546
 8547
 8548
 8549
 8550
 8551
 8552
 8553
 8554
 8555
 8556
 8557
 8558
 8559
 8560
 8561
 8562
 8563
 8564
 8565
 8566
 8567
 8568
 8569
 8570
 8571
 8572
 8573
 8574
 8575
 8576
 8577
 8578
 8579
 8580
 8581
 8582
 8583
 8584
 8585
 8586
 8587
 8588
 8589
 8590
 8591
 8592
 8593
 8594
 8595
 8596
 8597
 8598
 8599
 8600
 8601
 8602
 8603
 8604
 8605
 8606
 8607
 8608
 8609
 8610
 8611
 8612
 8613
 8614
 8615
 8616
 8617
 8618
 8619
 8620
 8621
 8622
 8623
 8624
 8625
 8626
 8627
 8628
 8629
 8630
 8631
 8632
 8633
 8634
 8635
 8636
 8637
 8638
 8639
 8640
 8641
 8642
 8643
 8644
 8645
 8646
 8647
 8648
 8649
 8650
 8651
 8652
 8653
 8654
 8655
 8656
 8657
 8658
 8659
 8660
 8661
 8662
 8663
 8664
 8665
 8666
 8667
 8668
 8669
 8670
 8671
 8672
 8673
 8674
 8675
 8676
 8677
 8678
 8679
 8680
 8681
 8682
 8683
 8684
 8685
 8686
 8687
 8688
 8689
 8690
 8691
 8692
 8693
 8694
 8695
 8696
 8697
 8698
 8699
 8700
 8701
 8702
 8703
 8704
 8705
 8706
 8707
 8708
 8709
 8710
 8711
 8712
 8713
 8714
 8715
 8716
 8717
 8718
 8719
 8720
 8721
 8722
 8723
 8724
 8725
 8726
 8727
 8728
 8729
 8730
 8731
 8732
 8733
 8734
 8735
 8736
 8737
 8738
 8739
 8740
 8741
 8742
 8743
 8744
 8745
 8746
 8747
 8748
 8749
 8750
 8751
 8752
 8753
 8754
 8755
 8756
 8757
 8758
 8759
 8760
 8761
 8762
 8763
 8764
 8765
 8766
 8767
 8768
 8769
 8770
 8771
 8772
 8773
 8774
 8775
 8776
 8777
 8778
 8779
 8780
 8781
 8782
 8783
 8784
 8785
 8786
 8787
 8788
 8789
 8790
 8791
 8792
 8793
 8794
 8795
 8796
 8797
 8798
 8799
 8800
 8801
 8802
 8803
 8804
 8805
 8806
 8807
 8808
 8809
 8810
 8811
 8812
 8813
 8814
 8815
 8816
 8817
 8818
 8819
 8820
 8821
 8822
 8823
 8824
 8825
 8826
 8827
 8828
 8829
 8830
 8831
 8832
 8833
 8834
 8835
 8836
 8837
 8838
 8839
 8840
 8841
 8842
 8843
 8844
 8845
 8846
 8847
 8848
 8849
 8850
 8851
 8852
 8853
 8854
 8855
 8856
 8857
 8858
 8859
 8860
 8861
 8862
 8863
 8864
 8865
 8866
 8867
 8868
 8869
 8870
 8871
 8872
 8873
 8874
 8875
 8876
 8877
 8878
 8879
 8880
 8881
 8882
 8883
 8884
 8885
 8886
 8887
 8888
 8889
 8890
 8891
 8892
 8893
 8894
 8895
 8896
 8897
 8898
 8899
 8900
 8901
 8902
 8903
 8904
 8905
 8906
 8907
 8908
 8909
 8910
 8911
 8912
 8913
 8914
 8915
 8916
 8917
 8918
 8919
 8920
 8921
 8922
 8923
 8924
 8925
 8926
 8927
 8928
 8929
 8930
 8931
 8932
 8933
 8934
 8935
 8936
 8937
 8938
 8939
 8940
 8941
 8942
 8943
 8944
 8945
 8946
 8947
 8948
 8949
 8950
 8951
 8952
 8953
 8954
 8955
 8956
 8957
 8958
 8959
 8960
 8961
 8962
 8963
 8964
 8965
 8966
 8967
 8968
 8969
 8970
 8971
 8972
 8973
 8974
 8975
 8976
 8977
 8978
 8979
 8980
 8981
 8982
 8983
 8984
 8985
 8986
 8987
 8988
 8989
 8990
 8991
 8992
 8993
 8994
 8995
 8996
 8997
 8998
 8999
 9000
 9001
 9002
 9003
 9004
 9005
 9006
 9007
 9008
 9009
 9010
 9011
 9012
 9013
 9014
 9015
 9016
 9017
 9018
 9019
 9020
 9021
 9022
 9023
 9024
 9025
 9026
 9027
 9028
 9029
 9030
 9031
 9032
 9033
 9034
 9035
 9036
 9037
 9038
 9039
 9040
 9041
 9042
 9043
 9044
 9045
 9046
 9047
 9048
 9049
 9050
 9051
 9052
 9053
 9054
 9055
 9056
 9057
 9058
 9059
 9060
 9061
 9062
 9063
 9064
 9065
 9066
 9067
 9068
 9069
 9070
 9071
 9072
 9073
 9074
 9075
 9076
 9077
 9078
 9079
 9080
 9081
 9082
 9083
 9084
 9085
 9086
 9087
 9088
 9089
 9090
 9091
 9092
 9093
 9094
 9095
 9096
 9097
 9098
 9099
 9100
 9101
 9102
 9103
 9104
 9105
 9106
 9107
 9108
 9109
 9110
 9111
 9112
 9113
 9114
 9115
 9116
 9117
 9118
 9119
 9120
 9121
 9122
 9123
 9124
 9125
 9126
 9127
 9128
 9129
 9130
 9131
 9132
 9133
 9134
 9135
 9136
 9137
 9138
 9139
 9140
 9141
 9142
 9143
 9144
 9145
 9146
 9147
 9148
 9149
 9150
 9151
 9152
 9153
 9154
 9155
 9156
 9157
 9158
 9159
 9160
 9161
 9162
 9163
 9164
 9165
 9166
 9167
 9168
 9169
 9170
 9171
 9172
 9173
 9174
 9175
 9176
 9177
 9178
 9179
 9180
 9181
 9182
 9183
 9184
 9185
 9186
 9187
 9188
 9189
 9190
 9191
 9192
 9193
 9194
 9195
 9196
 9197
 9198
 9199
 9200
 9201
 9202
 9203
 9204
 9205
 9206
 9207
 9208
 9209
 9210
 9211
 9212
 9213
 9214
 9215
 9216
 9217
 9218
 9219
 9220
 9221
 9222
 9223
 9224
 9225
 9226
 9227
 9228
 9229
 9230
 9231
 9232
 9233
 9234
 9235
 9236
 9237
 9238
 9239
 9240
 9241
 9242
 9243
 9244
 9245
 9246
 9247
 9248
 9249
 9250
 9251
 9252
 9253
 9254
 9255
 9256
 9257
 9258
 9259
 9260
 9261
 9262
 9263
 9264
 9265
 9266
 9267
 9268
 9269
 9270
 9271
 9272
 9273
 9274
 9275
 9276
 9277
 9278
 9279
 9280
 9281
 9282
 9283
 9284
 9285
 9286
 9287
 9288
 9289
 9290
 9291
 9292
 9293
 9294
 9295
 9296
 9297
 9298
 9299
 9300
 9301
 9302
 9303
 9304
 9305
 9306
 9307
 9308
 9309
 9310
 9311
 9312
 9313
 9314
 9315
 9316
 9317
 9318
 9319
 9320
 9321
 9322
 9323
 9324
 9325
 9326
 9327
 9328
 9329
 9330
 9331
 9332
 9333
 9334
 9335
 9336
 9337
 9338
 9339
 9340
 9341
 9342
 9343
 9344
 9345
 9346
 9347
 9348
 9349
 9350
 9351
 9352
 9353
 9354
 9355
 9356
 9357
 9358
 9359
 9360
 9361
 9362
 9363
 9364
 9365
 9366
 9367
 9368
 9369
 9370
 9371
 9372
 9373
 9374
 9375
 9376
 9377
 9378
 9379
 9380
 9381
 9382
 9383
 9384
 9385
 9386
 9387
 9388
 9389
 9390
 9391
 9392
 9393
 9394
 9395
 9396
 9397
 9398
 9399
 9400
 9401
 9402
 9403
 9404
 9405
 9406
 9407
 9408
 9409
 9410
 9411
 9412
 9413
 9414
 9415
 9416
 9417
 9418
 9419
 9420
 9421
 9422
 9423
 9424
 9425
 9426
 9427
 9428
 9429
 9430
 9431
 9432
 9433
 9434
 9435
 9436
 9437
 9438
 9439
 9440
 9441
 9442
 9443
 9444
 9445
 9446
 9447
 9448
 9449
 9450
 9451
 9452
 9453
 9454
 9455
 9456
 9457
 9458
 9459
 9460
 9461
 9462
 9463
 9464
 9465
 9466
 9467
 9468
 9469
 9470
 9471
 9472
 9473
 9474
 9475
 9476
 9477
 9478
 9479
 9480
 9481
 9482
 9483
 9484
 9485
 9486
 9487
 9488
 9489
 9490
 9491
 9492
 9493
 9494
 9495
 9496
 9497
 9498
 9499
 9500
 9501
 9502
 9503
 9504
 9505
 9506
 9507
 9508
 9509
 9510
 9511
 9512
 9513
 9514
 9515
 9516
 9517
 9518
 9519
 9520
 9521
 9522
 9523
 9524
 9525
 9526
 9527
 9528
 9529
 9530
 9531
 9532
 9533
 9534
 9535
 9536
 9537
 9538
 9539
 9540
 9541
 9542
 9543
 9544
 9545
 9546
 9547
 9548
 9549
 9550
 9551
 9552
 9553
 9554
 9555
 9556
 9557
 9558
 9559
 9560
 9561
 9562
 9563
 9564
 9565
 9566
 9567
 9568
 9569
 9570
 9571
 9572
 9573
 9574
 9575
 9576
 9577
 9578
 9579
 9580
 9581
 9582
 9583
 9584
 9585
 9586
 9587
 9588
 9589
 9590
 9591
 9592
 9593
 9594
 9595
 9596
 9597
 9598
 9599
 9600
 9601
 9602
 9603
 9604
 9605
 9606
 9607
 9608
 9609
 9610
 9611
 9612
 9613
 9614
 9615
 9616
 9617
 9618
 9619
 9620
 9621
 9622
 9623
 9624
 9625
 9626
 9627
 9628
 9629
 9630
 9631
 9632
 9633
 9634
 9635
 9636
 9637
 9638
 9639
 9640
 9641
 9642
 9643
 9644
 9645
 9646
 9647
 9648
 9649
 9650
 9651
 9652
 9653
 9654
 9655
 9656
 9657
 9658
 9659
 9660
 9661
 9662
 9663
 9664
 9665
 9666
 9667
 9668
 9669
 9670
 9671
 9672
 9673
 9674
 9675
 9676
 9677
 9678
 9679
 9680
 9681
 9682
 9683
 9684
 9685
 9686
 9687
 9688
 9689
 9690
 9691
 9692
 9693
 9694
 9695
 9696
 9697
 9698
 9699
 9700
 9701
 9702
 9703
 9704
 9705
 9706
 9707
 9708
 9709
 9710
 9711
 9712
 9713
 9714
 9715
 9716
 9717
 9718
 9719
 9720
 9721
 9722
 9723
 9724
 9725
 9726
 9727
 9728
 9729
 9730
 9731
 9732
 9733
 9734
 9735
 9736
 9737
 9738
 9739
 9740
 9741
 9742
 9743
 9744
 9745
 9746
 9747
 9748
 9749
 9750
 9751
 9752
 9753
 9754
 9755
 9756
 9757
 9758
 9759
 9760
 9761
 9762
 9763
 9764
 9765
 9766
 9767
 9768
 9769
 9770
 9771
 9772
 9773
 9774
 9775
 9776
 9777
 9778
 9779
 9780
 9781
 9782
 9783
 9784
 9785
 9786
 9787
 9788
 9789
 9790
 9791
 9792
 9793
 9794
 9795
 9796
 9797
 9798
 9799
 9800
 9801
 9802
 9803
 9804
 9805
 9806
 9807
 9808
 9809
 9810
 9811
 9812
 9813
 9814
 9815
 9816
 9817
 9818
 9819
 9820
 9821
 9822
 9823
 9824
 9825
 9826
 9827
 9828
 9829
 9830
 9831
 9832
 9833
 9834
 9835
 9836
 9837
 9838
 9839
 9840
 9841
 9842
 9843
 9844
 9845
 9846
 9847
 9848
 9849
 9850
 9851
 9852
 9853
 9854
 9855
 9856
 9857
 9858
 9859
 9860
 9861
 9862
 9863
 9864
 9865
 9866
 9867
 9868
 9869
 9870
 9871
 9872
 9873
 9874
 9875
 9876
 9877
 9878
 9879
 9880
 9881
 9882
 9883
 9884
 9885
 9886
 9887
 9888
 9889
 9890
 9891
 9892
 9893
 9894
 9895
 9896
 9897
 9898
 9899
 9900
 9901
 9902
 9903
 9904
 9905
 9906
 9907
 9908
 9909
 9910
 9911
 9912
 9913
 9914
 9915
 9916
 9917
 9918
 9919
 9920
 9921
 9922
 9923
 9924
 9925
 9926
 9927
 9928
 9929
 9930
 9931
 9932
 9933
 9934
 9935
 9936
 9937
 9938
 9939
 9940
 9941
 9942
 9943
 9944
 9945
 9946
 9947
 9948
 9949
 9950
 9951
 9952
 9953
 9954
 9955
 9956
 9957
 9958
 9959
 9960
 9961
 9962
 9963
 9964
 9965
 9966
 9967
 9968
 9969
 9970
 9971
 9972
 9973
 9974
 9975
 9976
 9977
 9978
 9979
 9980
 9981
 9982
 9983
 9984
 9985
 9986
 9987
 9988
 9989
 9990
 9991
 9992
 9993
 9994
 9995
 9996
 9997
 9998
 9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
class OTCS:
    """Used to automate stettings in OpenText Extended ECM."""

    _config: dict
    _cookie = None
    _otcs_ticket = None
    _otds_ticket = None
    _data: Data = None
    _thread_number = 3
    _download_dir = ""

    # Handle concurrent HTTP requests that may run into 401 errors and
    # re-authentication at the same time:
    _authentication_lock = threading.Lock()
    _authentication_condition = threading.Condition(_authentication_lock)
    _authentication_semaphore = threading.Semaphore(
        1
    )  # only 1 thread should handle the re-authentication
    _session_lock = threading.Lock()

    @classmethod
    def date_is_newer(cls, date_old: str, date_new: str) -> bool:
        """Compare two dates, typically create or modification dates

        Args:
            date_old (str): the date that is considered older
            date_new (str): the date that is considered newer

        Returns:
            bool: True if date_new is indeed newer as date_old, False otherwise
        """

        if not date_old or not date_new:
            return True

        # Define the date formats
        format1 = "%Y-%m-%dT%H:%M:%SZ"  # Format: "YYYY-MM-DDTHH:MM:SSZ"
        format2 = "%Y-%m-%d %H:%M:%S"  # Format: "YYY-MM-DD HH:MM:SS"
        format3 = "%Y-%m-%dT%H:%M:%S"  # Format: "YYY-MM-DD HH:MM:SS"
        format4 = "%Y-%m-%d"  # Format: "YYY-MM-DD"

        # Parse the dates
        try:
            if "T" in date_old and "Z" in date_old:
                old_date = datetime.strptime(date_old, format1)
            elif " " in date_old:
                old_date = datetime.strptime(date_old, format2)
            elif "T" in date_old:
                old_date = datetime.strptime(date_old, format3)
            else:
                old_date = datetime.strptime(date_old, format4)
        except ValueError:
            return True

        try:
            if "T" in date_new and "Z" in date_new:
                new_date = datetime.strptime(date_new, format1)
            elif " " in date_new:
                new_date = datetime.strptime(date_new, format2)
            elif "T" in date_new:
                new_date = datetime.strptime(date_new, format3)
            else:
                new_date = datetime.strptime(date_new, format4)
        except ValueError:
            return True

        # Compare the dates
        return new_date > old_date

    # end method definition

    def __init__(
        self,
        protocol: str,
        hostname: str,
        port: int,
        public_url: str | None = None,
        username: str | None = None,
        password: str | None = None,
        user_partition: str = "Content Server Members",
        resource_name: str = "cs",
        default_license: str = "X3",
        otds_ticket: str | None = None,
        base_path: str = "/cs/cs",
        thread_number: int = 3,
        download_dir: str = "/tmp/contentserver",
        feme_uri: str | None = None,
    ):
        """Initialize the OTCS object

        Args:
            protocol (str): Either http or https.
            hostname (str): The hostname of Extended ECM server to communicate with.
            port (int): The port number used to talk to the Extended ECM server.
            public_url (str): public (external) URL
            username (str, optional): The admin user name of Extended ECM. Optional if otds_ticket is provided.
            password (str, optional): The admin password of Extended ECM. Optional if otds_ticket is provided.
            user_partition (str): Name of the OTDS partition for OTCS users. Default is "Content Server Members".
            resource_name (str, optional): Name of the OTDS resource for OTCS. Dault is "cs".
            default_license (str, optional): name of the default user license. Default is "X3".
            otds_ticket (str, optional): Authentication ticket of OTDS
        """

        # Initialize otcs_config as an empty dictionary
        otcs_config = {}

        if hostname:
            otcs_config["hostname"] = hostname
        else:
            otcs_config["hostname"] = "otcs-admin-0"

        if protocol:
            otcs_config["protocol"] = protocol
        else:
            otcs_config["protocol"] = "http"

        if port:
            otcs_config["port"] = port
        else:
            otcs_config["port"] = 8080

        otcs_config["publicUrl"] = public_url

        if username:
            otcs_config["username"] = username
        else:
            otcs_config["username"] = "admin"

        if password:
            otcs_config["password"] = password
        else:
            otcs_config["password"] = ""

        if user_partition:
            otcs_config["partition"] = user_partition
        else:
            otcs_config["partition"] = ""

        if resource_name:
            otcs_config["resource"] = resource_name
        else:
            otcs_config["resource"] = ""

        if default_license:
            otcs_config["license"] = default_license
        else:
            otcs_config["license"] = ""

        otcs_config["feme_uri"] = feme_uri

        otcs_base_url = protocol + "://" + otcs_config["hostname"]
        if str(port) not in ["80", "443"]:
            otcs_base_url += ":{}".format(port)
        otcs_config["baseUrl"] = otcs_base_url
        otcs_support_url = otcs_base_url + "/cssupport"
        otcs_config["supportUrl"] = otcs_support_url

        if public_url is None:
            public_url = otcs_base_url

        otcs_public_support_url = public_url + "/cssupport"
        otcs_config["supportPublicUrl"] = otcs_public_support_url

        otcs_config["configuredUrl"] = otcs_support_url + "/csconfigured"

        otcs_url = otcs_base_url + base_path
        otcs_config["csUrl"] = otcs_url
        otcs_public_url = public_url + base_path
        otcs_config["csPublicUrl"] = otcs_public_url

        otcs_rest_url = otcs_url + "/api"
        otcs_config["restUrl"] = otcs_rest_url

        otcs_config["isReady"] = otcs_rest_url + "/v1/ping"
        otcs_config["authenticationUrl"] = otcs_rest_url + "/v1/auth"
        otcs_config["serverInfoUrl"] = otcs_rest_url + "/v1/serverinfo"
        otcs_config["membersUrl"] = otcs_rest_url + "/v1/members"
        otcs_config["membersUrlv2"] = otcs_rest_url + "/v2/members"
        otcs_config["nodesUrl"] = otcs_rest_url + "/v1/nodes"
        otcs_config["nodesUrlv2"] = otcs_rest_url + "/v2/nodes"
        otcs_config["doctemplatesUrl"] = otcs_rest_url + "/v2/doctemplates"
        otcs_config["nicknameUrl"] = otcs_rest_url + "/v2/nicknames"
        otcs_config["importSettingsUrl"] = otcs_rest_url + "/v2/import/settings/admin"
        otcs_config["searchUrl"] = otcs_rest_url + "/v2/search"
        otcs_config["volumeUrl"] = otcs_rest_url + "/v2/volumes"
        otcs_config["externalSystemUrl"] = otcs_rest_url + "/v2/externalsystems"
        otcs_config["businessObjectsUrl"] = otcs_rest_url + "/v2/businessobjects"
        otcs_config["businessObjectTypesUrl"] = (
            otcs_rest_url + "/v2/businessobjecttypes"
        )
        otcs_config["businessObjectsSearchUrl"] = (
            otcs_rest_url + "/v2/forms/businessobjects/search"
        )
        otcs_config["businessWorkspaceTypesUrl"] = (
            otcs_rest_url + "/v2/businessworkspacetypes"
        )
        otcs_config["businessworkspacecreateform"] = (
            otcs_rest_url + "/v2/forms/businessworkspaces/create"
        )
        otcs_config["businessWorkspacesUrl"] = otcs_rest_url + "/v2/businessworkspaces"
        otcs_config["uniqueNamesUrl"] = otcs_rest_url + "/v2/uniquenames"
        otcs_config["favoritesUrl"] = otcs_rest_url + "/v2/members/favorites"
        otcs_config["webReportsUrl"] = otcs_rest_url + "/v1/webreports"
        otcs_config["csApplicationsUrl"] = otcs_rest_url + "/v2/csapplications"
        otcs_config["xEngProjectTemplateUrl"] = (
            otcs_rest_url + "/v2/xengcrt/projecttemplate"
        )
        otcs_config["rsisUrl"] = otcs_rest_url + "/v2/rsis"
        otcs_config["rsiSchedulesUrl"] = otcs_rest_url + "/v2/rsischedules"
        otcs_config["recordsManagementUrl"] = otcs_rest_url + "/v1/recordsmanagement"
        otcs_config["recordsManagementUrlv2"] = otcs_rest_url + "/v2/recordsmanagement"
        otcs_config["userSecurityUrl"] = otcs_rest_url + "/v2/members/usersecurity"
        otcs_config["physicalObjectsUrl"] = otcs_rest_url + "/v1/physicalobjects"
        otcs_config["securityClearancesUrl"] = otcs_rest_url + "/v1/securityclearances"
        otcs_config["holdsUrl"] = otcs_rest_url + "/v1/holds"
        otcs_config["holdsUrlv2"] = otcs_rest_url + "/v2/holds"
        otcs_config["validationUrl"] = otcs_rest_url + "/v1/validation/nodes/names"
        otcs_config["aiUrl"] = otcs_rest_url + "/v2/ai/nodes"
        otcs_config["recycleBinUrl"] = otcs_rest_url + "/v2/volumes/recyclebin"
        otcs_config["processUrl"] = otcs_rest_url + "/v2/processes"
        otcs_config["workflowUrl"] = otcs_rest_url + "/v2/workflows"
        otcs_config["docWorkflowUrl"] = otcs_rest_url + "/v2/docworkflows"
        otcs_config["draftProcessUrl"] = otcs_rest_url + "/v2/draftprocesses"
        otcs_config["draftProcessFormUrl"] = otcs_rest_url + "/v1/forms/draftprocesses"
        otcs_config["processTaskUrl"] = (
            otcs_rest_url + "/v1/forms/processes/tasks/update"
        )

        self._config = otcs_config
        self._otds_ticket = otds_ticket
        self._data = Data()
        self._thread_number = thread_number
        self._download_dir = download_dir
        self._semaphore = threading.BoundedSemaphore(value=thread_number)

    # end method definition

    def config(self) -> dict:
        """Returns the configuration dictionary

        Returns:
            dict: Configuration dictionary
        """
        return self._config

    # end method definition

    def cookie(self) -> dict:
        """Returns the login cookie of Extended ECM.
           This is set by the authenticate() method

        Returns:
            dict: Estended ECM cookie
        """
        return self._cookie

    # end method definition

    def otcs_ticket(self) -> str | None:
        """Return the OTCS ticket

        Returns:
            str: String with the OTCS ticket
        """

        return self._otcs_ticket

    # end method definition

    def credentials(self) -> dict:
        """Get credentials (username + password)

        Returns:
            dict: dictionary with username and password
        """
        return {
            "username": self.config()["username"],
            "password": self.config()["password"],
        }

    # end method definition

    def set_credentials(self, username: str = "admin", password: str = ""):
        """Set the credentials for Extended ECM based on username and password.

        Args:
            username (str, optional): Username. Defaults to "admin".
            password (str, optional): Password of the user. Defaults to "".
        """

        self.config()["username"] = username
        self.config()["password"] = password

    # end method definition

    def hostname(self) -> str:
        """Returns the hostname of Extended ECM (e.g. "otcs")

        Returns:
            str: hostname
        """
        return self.config()["hostname"]

    # end method definition

    def set_hostname(self, hostname: str):
        """Sets the hostname of Extended ECM

        Args:
            hostname (str): new hostname
        """
        self.config()["hostname"] = hostname

    # end method definition

    def base_url(self) -> str:
        """Returns the base URL of Extended ECM

        Returns:
            str: base URL
        """
        return self.config()["baseUrl"]

    # end method definition

    def cs_url(self) -> str:
        """Returns the Extended ECM URL

        Returns:
            str: Extended ECM URL
        """
        return self.config()["csUrl"]

    # end method definition

    def cs_public_url(self) -> str:
        """Returns the public (external) Extended ECM URL (incl. base_path /cs/cs )

        Returns:
            str: Extended ECM Public URL
        """
        return self.config()["csPublicUrl"]

    # end method definition

    def cs_support_url(self) -> str:
        """Returns the Extended ECM Support URL

        Returns:
            str: Extended ECM Support URL
        """
        return self.config()["supportUrl"]

    # end method definition

    def cs_support_public_url(self) -> str:
        """Returns the Extended ECM Public Support URL

        Returns:
            str: Extended ECM Public Support URL
        """
        return self.config()["supportPublicUrl"]

    # end method definition

    def rest_url(self) -> str:
        """Returns the REST URL of Extended ECM

        Returns:
            str: REST URL
        """
        return self.config()["restUrl"]

    # end method definition

    def get_data(self) -> Data:
        """Get the Data object that holds all loaded Content Server items (see method load_items())

        Returns:
            Data: Datastructure with all processed articles.
        """

        return self._data

    # end method definition

    def request_form_header(self) -> dict:
        """Deliver the request header used for the CRUD REST API calls.
           Consists of Cookie + Form Headers (see global variable)

        Args:
            None.
        Return:
            dict: request header values
        """

        # create union of two dicts: cookie and headers
        # (with Python 3.9 this would be easier with the "|" operator)
        request_header = {}
        request_header.update(self.cookie())
        request_header.update(REQUEST_FORM_HEADERS)

        return request_header

    # end method definition

    def request_json_header(self) -> dict:
        """Deliver the request header for REST calls that require content type application/json.
           Consists of Cookie + Json Headers (see global variable)

        Args:
            None.
        Return:
            dict: request header values
        """

        # create union of two dicts: cookie and headers
        # (with Python 3.9 this would be easier with the "|" operator)
        request_header = {}
        request_header.update(self.cookie())
        request_header.update(REQUEST_JSON_HEADERS)

        return request_header

    # end method definition

    def request_download_header(self) -> dict:
        """Deliver the request header used for the CRUD REST API calls.
           Consists of Cookie + Form Headers (see global vasriable)

        Args:
            None.
        Return:
            dict: request header values
        """

        # create union of two dicts: cookie and headers
        # (with Python 3.9 this would be easier with the "|" operator)
        request_header = {}
        request_header.update(self.cookie())
        request_header.update(REQUEST_DOWNLOAD_HEADERS)

        return request_header

    # end method definition

    def do_request(
        self,
        url: str,
        method: str = "GET",
        headers: dict | None = None,
        data: dict | None = None,
        json_data: dict | None = None,
        files: dict | None = None,
        timeout: int | None = REQUEST_TIMEOUT,
        show_error: bool = True,
        show_warning: bool = False,
        warning_message: str = "",
        failure_message: str = "",
        success_message: str = "",
        max_retries: int = REQUEST_MAX_RETRIES,
        retry_forever: bool = False,
        parse_request_response: bool = True,
    ) -> dict | None:
        """Call an Extended ECM REST API in a safe way

        Args:
            url (str): URL to send the request to.
            method (str, optional): HTTP method (GET, POST, etc.). Defaults to "GET".
            headers (dict | None, optional): Request Headers. Defaults to None.
            data (dict | None, optional): Request payload. Defaults to None
            files (dict | None, optional): Dictionary of {"name": file-tuple} for multipart encoding upload.
                                           file-tuple can be a 2-tuple ("filename", fileobj) or a 3-tuple ("filename", fileobj, "content_type")
            timeout (int | None, optional): Timeout for the request in seconds. Defaults to REQUEST_TIMEOUT.
            show_error (bool, optional): Whether or not an error should be logged in case of a failed REST call.
                                         If False, then only a warning is logged. Defaults to True.
            warning_message (str, optional): Specific warning message. Defaults to "". If not given the error_message will be used.
            failure_message (str, optional): Specific error message. Defaults to "".
            success_message (str, optional): Specific success message. Defaults to "".
            max_retries (int, optional): How many retries on Connection errors? Default is REQUEST_MAX_RETRIES.
            retry_forever (bool, optional): Eventually wait forever - without timeout. Defaults to False.
            parse_request_response (bool, optional): should the response.text be interpreted as json and loaded into a dictionary. True is the default.

        Returns:
            dict | None: Response of Extended ECM REST API or None in case of an error.
        """

        # In case of an expired session we reauthenticate and
        # try 1 more time. Session expiration should not happen
        # twice in a row:
        retries = 0

        while True:
            try:
                # We protect this with a lock to not read
                # a cookie that is in process of being renewed
                # by another thread:
                with self._session_lock:
                    request_cookie = self.cookie()
                response = requests.request(
                    method=method,
                    url=url,
                    data=data,
                    json=json_data,
                    files=files,
                    headers=headers,
                    cookies=request_cookie,
                    timeout=timeout,
                )

                if response.ok:
                    if success_message:
                        logger.info(success_message)
                    if parse_request_response:
                        return self.parse_request_response(response)
                    else:
                        return response
                # Check if Session has expired - then re-authenticate and try once more
                elif response.status_code == 401 and retries == 0:
                    # Try to reauthenticate:
                    self.reauthenticate(request_cookie=request_cookie, thread_safe=True)
                    retries += 1
                    logger.debug("Reauthentication complete. Retry = %s", str(retries))
                    logger.debug(
                        "Old cookie -> %s, new cookie -> %s",
                        str(request_cookie),
                        str(self.cookie()),
                    )
                elif response.status_code == 500 and "already exists" in response.text:
                    logger.warning(
                        (
                            warning_message
                            + " (it already exists); details -> {}".format(
                                response.text
                            )
                            if warning_message
                            else failure_message
                            + " (it already exists); details -> {}".format(
                                response.text
                            )
                        ),
                    )
                    if parse_request_response:
                        return self.parse_request_response(response)
                    else:
                        return response
                else:
                    # Handle plain HTML responses to not pollute the logs
                    content_type = response.headers.get("content-type", None)
                    if content_type == "text/html":
                        response_text = "HTML content (only printed in debug log)"
                    else:
                        response_text = response.text

                    if show_error:
                        logger.error(
                            "%s; status -> %s/%s; error -> %s",
                            failure_message,
                            response.status_code,
                            HTTPStatus(response.status_code).phrase,
                            response_text,
                        )
                    elif show_warning:
                        logger.warning(
                            "%s; status -> %s/%s; warning -> %s",
                            warning_message if warning_message else failure_message,
                            response.status_code,
                            HTTPStatus(response.status_code).phrase,
                            response_text,
                        )

                    if content_type == "text/html":
                        logger.debug(
                            "%s; status -> %s/%s; debug output -> %s",
                            failure_message,
                            response.status_code,
                            HTTPStatus(response.status_code).phrase,
                            response.text,
                        )

                    return None
            except requests.exceptions.Timeout:
                if retries <= max_retries:
                    logger.warning(
                        "Request timed out. Retrying in %s seconds...",
                        str(REQUEST_RETRY_DELAY),
                    )
                    retries += 1
                    time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
                else:
                    logger.error(
                        "%s; timeout error",
                        failure_message,
                    )
                    if retry_forever:
                        # If it fails after REQUEST_MAX_RETRIES retries we let it wait forever
                        logger.warning("Turn timeouts off and wait forever...")
                        timeout = None
                    else:
                        return None
            except requests.exceptions.ConnectionError:
                if retries <= max_retries:
                    logger.warning(
                        "Connection error. Retrying in %s seconds...",
                        str(REQUEST_RETRY_DELAY),
                    )
                    retries += 1
                    time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
                else:
                    logger.error(
                        "%s; connection error",
                        failure_message,
                    )
                    if retry_forever:
                        # If it fails after REQUEST_MAX_RETRIES retries we let it wait forever
                        logger.warning("Turn timeouts off and wait forever...")
                        timeout = None
                        time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
                    else:
                        return None
            # end try
            logger.debug(
                "Retrying REST API %s call -> %s... (retry = %s, cookie -> %s)",
                method,
                url,
                str(retries),
                str(self.cookie()),
            )
        # end while True

    # end method definition

    def parse_request_response(
        self,
        response_object: object,
        additional_error_message: str = "",
        show_error: bool = True,
    ) -> dict | None:
        """Converts the text property of a request response object to a Python dict in a safe way
            that also handles exceptions.

            Content Server may produce corrupt response when it gets restarted
            or hitting resource limits. So we try to avoid a fatal error and bail
            out more gracefully.

        Args:
            response_object (object): this is reponse object delivered by the request call
            additional_error_message (str): print a custom error message
            show_error (bool): if True log an error, if False log a warning

        Returns:
            dict: response or None in case of an error
        """

        if not response_object:
            return None

        if not response_object.text:
            logger.warning("Response text is empty. Cannot decode response.")
            return None

        try:
            dict_object = json.loads(response_object.text)
        except json.JSONDecodeError as exception:
            if additional_error_message:
                message = "Cannot decode response as JSon. {}; error -> {}".format(
                    additional_error_message, exception
                )
            else:
                message = "Cannot decode response as JSon; error -> {}".format(
                    exception
                )
            if show_error:
                logger.error(message)
            else:
                logger.debug(message)
            return None
        else:
            return dict_object

    # end method definition

    def lookup_result_value(
        self, response: dict, key: str, value: str, return_key: str
    ) -> str | None:
        """Lookup a property value based on a provided key / value pair in the
           response properties of an Extended ECM REST API call.

        Args:
            response (dict): REST response from an OTCS REST Call
            key (str): property name (key)
            value (str): value to find in the item with the matching key
            return_key (str): determines which value to return based on the name of the dict key
        Returns:
            str: value of the property with the key defined in "return_key"
                 or None if the lookup fails
        """

        if not response:
            return None
        if not "results" in response:
            return None

        results = response["results"]
        # check if results is a list or a dict (both is possible -
        # dependent on the actual REST API):
        if isinstance(results, dict):
            # result is a dict - we don't need index value:
            data = results["data"]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                properties = data["properties"]
                if (
                    key in properties
                    and properties[key] == value
                    and return_key in properties
                ):
                    return properties[return_key]
                else:
                    return None
            elif isinstance(data, list):
                # data is a list - this has typically just one item, so we use 0 as index
                for item in data:
                    properties = item["properties"]
                    if (
                        key in properties
                        and properties[key] == value
                        and return_key in properties
                    ):
                        return properties[return_key]
                return None
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s", str(type(data))
                )
                return None
        elif isinstance(results, list):
            # result is a list - we need index value
            for result in results:
                data = result["data"]
                if isinstance(data, dict):
                    # data is a dict - we don't need index value:
                    properties = data["properties"]
                    if (
                        key in properties
                        and properties[key] == value
                        and return_key in properties
                    ):
                        return properties[return_key]
                elif isinstance(data, list):
                    # data is a list we iterate through the list and try to find the key:
                    for item in data:
                        properties = item["properties"]
                        if (
                            key in properties
                            and properties[key] == value
                            and return_key in properties
                        ):
                            return properties[return_key]
                else:
                    logger.error(
                        "Data needs to be a list or dict but it is -> %s",
                        str(type(data)),
                    )
                    return None
            return None
        else:
            logger.error(
                "Result needs to be a list or dict but it is -> %s", str(type(results))
            )
            return None

    # end method definition

    def exist_result_item(
        self, response: dict, key: str, value: str, property_name: str = "properties"
    ) -> bool:
        """Check existence of key / value pair in the response properties of an Extended ECM REST API call.

        Args:
            response (dict): REST response from an OTCS REST Call
            key (str): property name (key)
            value (str): value to find in the item with the matching key
            property_name (str, optional): name of the substructure that includes the values
        Returns:
            bool: True if the value was found, False otherwise
        """

        if not response:
            return False
        if not "results" in response:
            return False

        results = response["results"]
        # check if results is a list or a dict (both is possible - dependent on the actual REST API):
        if isinstance(results, dict):
            # result is a dict - we don't need index value:
            if not "data" in results:
                return False
            data = results["data"]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                if property_name and not property_name in data:
                    logger.error(
                        "There's no dictionary -> '%s' in data -> %s",
                        property_name,
                        data,
                    )
                    return False
                properties = data[property_name]
                if isinstance(properties, dict):
                    if key in properties:
                        return properties[key] == value
                    else:
                        return False
                elif isinstance(properties, list):
                    # properties is a list we iterate through the list and try to find the key:
                    for item in properties:
                        if key in item and item[key] == value:
                            return True
                else:
                    logger.error(
                        "Properties needs to be a list or dict but it is -> %s",
                        str(type(properties)),
                    )
                    return False
            elif isinstance(data, list):
                # data is a list
                for item in data:
                    if property_name and not property_name in item:
                        logger.error(
                            "There's no dictionary -> '%s' in the data list item -> %s",
                            property_name,
                            item,
                        )
                        continue
                    # if properties if passed as empty string then we assume that
                    # the key fields are directly in the item dictionary. This is
                    # the case e.g. with the V2 Proxy APIs
                    if not property_name:
                        properties = item
                    else:
                        properties = item[property_name]
                    if key in properties and properties[key] == value:
                        return True
                return False
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s", str(type(data))
                )
                return False
        elif isinstance(results, list):
            # result is a list - we need index value
            for result in results:
                if not "data" in result:
                    continue
                data = result["data"]
                if isinstance(data, dict):
                    # data is a dict - we don't need index value:
                    properties = data[property_name]
                    if key in properties and properties[key] == value:
                        return True
                elif isinstance(data, list):
                    # data is a list we iterate through the list and try to find the key:
                    for item in data:
                        properties = item[property_name]
                        if key in properties and properties[key] == value:
                            return True
                else:
                    logger.error(
                        "Data needs to be a list or dict but it is -> %s",
                        str(type(data)),
                    )
                    return False
            return False
        else:
            logger.error(
                "Result needs to be a list or dict but it is -> %s", str(type(results))
            )
            return False

    # end method definition

    def get_result_value(
        self,
        response: dict,
        key: str,
        index: int = 0,
        property_name: str = "properties",
        show_error: bool = True,
    ) -> str | None:
        """Read an item value from the REST API response. This is considering
           the most typical structures delivered by V2 REST API of Extended ECM.
           See developer.opentext.com for more details.

        Args:
            response (dict): REST API response object
            key (str): key to find (e.g. "id", "name", ...)
            index (int, optional): In case a list of results is delivered the index
                                   to use (1st element has index  0). Defaults to 0.
            property_name (str, optional): name of the sub dictionary holding the actual values.
                                           Default is "properties".
        Returns:
            str: value of the item with the given key for None if no value is found for the given key.
        """

        # First do some sanity checks:
        if not response:
            logger.debug("Empty REST response - returning None")
            return None
        if not "results" in response:
            if show_error:
                logger.error("No 'results' key in REST response - returning None")
            return None

        results = response["results"]
        if not results:
            logger.debug("No results found!")
            return None

        # check if results is a list or a dict (both is possible - dependent on the actual REST API):
        if isinstance(results, dict):
            # result is a dict - we don't need index value

            # this is a special treatment for the businessworkspaces REST API - it returns
            # for "Create business workspace" the ID directly in the results dict (without data substructure)
            if key in results:
                return results[key]
            data = results["data"]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                properties = data[property_name]
            elif isinstance(data, list):
                # data is a list - this has typically just one item, so we use 0 as index
                properties = data[0][property_name]
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s", str(type(data))
                )
                return None
            logger.debug("Properties of results (dict) -> %s", str(properties))
            # For nearly all OTCS REST Calls perperties is a dict:
            if isinstance(properties, dict):
                if not key in properties:
                    if show_error:
                        logger.error("Key -> '%s' is not in result properties!", key)
                    return None
                return properties[key]
            # but there are some strange ones that have other names for
            # properties and may use a list - see e.g. /v2/holds
            elif isinstance(properties, list):
                if index > len(properties) - 1:
                    logger.error(
                        "Illegal Index -> %s given. List has only -> %s elements!",
                        str(index),
                        str(len(properties)),
                    )
                    return None
                return properties[index][key]
            else:
                logger.error(
                    "Properties needs to be a list or dict but it is -> %s",
                    str(type(properties)),
                )
                return None
        elif isinstance(results, list):
            # result is a list - we need a valid index:
            if index > len(results) - 1:
                logger.error(
                    "Illegal Index -> %s given. List has only -> %s elements!",
                    str(index),
                    str(len(results)),
                )
                return None
            data = results[index]["data"]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                properties = data[property_name]
            elif isinstance(data, list):
                # data is a list - this has typically just one item, so we use 0 as index
                properties = data[0][property_name]
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s", str(type(data))
                )
                return None
            logger.debug(
                "Properties of results (list, index -> %s) -> %s",
                str(index),
                properties,
            )
            if not key in properties:
                if show_error:
                    logger.error("Key -> '%s' is not in result properties!", key)
                return None
            return properties[key]
        else:
            logger.error(
                "Result needs to be a list or dict but it is -> %s", str(type(results))
            )
            return None

    # end method definition

    def get_result_values(
        self,
        response: dict,
        key: str,
        property_name: str = "properties",
        data_name: str = "data",
    ) -> list | None:
        """Read an item value from the REST API response. This is considering
           the most typical structures delivered by V2 REST API of Extended ECM.
           See developer.opentext.com for more details.

        Args:
            response (dict): REST API response object
            key (str): key to find (e.g. "id", "name", ...)
            property_name (str, optional): name of the sub dictionary holding the actual values.
                                           Default is "properties".
            data_name (str, optional): name of the sub dictionary holding the data. Default = "data"
        Returns:
            str: value of the item with the given key for None if no value is found for the given key.
        """

        # First do some sanity checks:
        if not response:
            logger.debug("Empty REST response - returning None")
            return None
        if not "results" in response:
            logger.error("No 'results' key in REST response - returning None")
            return None

        results = response["results"]
        if not results:
            logger.debug("No results found!")
            return None

        # check if results is a list or a dict (both is possible - dependent on the actual REST API):
        if isinstance(results, dict):
            # result is a dict - we don't need index value

            # this is a special treatment for the businessworkspaces REST API - it returns
            # for "Create business workspace" the ID directly in the results dict (without data substructure)
            if key in results:
                return [results[key]]
            data = results[data_name]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                properties = data[property_name]
            elif isinstance(data, list):
                # data is a list - this has typically just one item, so we use 0 as index
                if property_name:
                    properties = data[0][property_name]
                    logger.debug("Properties of results (dict) -> %s", str(properties))
                else:
                    properties = data
                    logger.debug(
                        "Response does not have properties structure. Using data structure directly."
                    )
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s", str(type(data))
                )
                return None
            # For nearly all OTCS REST Calls properties is a dict:
            if isinstance(properties, dict):
                if not key in properties:
                    logger.error("Key -> '%s' is not in result properties!", key)
                    return None
                return [properties[key]]
            # but there are some strange ones that have other names for
            # properties and may use a list - see e.g. /v2/holds
            elif isinstance(properties, list):
                return [item[key] for item in properties]
            else:
                logger.error(
                    "Properties needs to be a list or dict but it is -> %s",
                    str(type(properties)),
                )
                return None
        elif isinstance(results, list):
            return [item[data_name][property_name][key] for item in results]
        else:
            logger.error(
                "Result needs to be a list or dict but it is -> %s", str(type(results))
            )
            return None

    # end method definition

    def is_configured(self) -> bool:
        """Checks if the Content Server pod is configured to receive requests.

        Args:
            None.
        Returns:
            bool: True if pod is ready. False if pod is not yet ready.
        """

        request_url = self.config()["configuredUrl"]

        logger.debug("Trying to retrieve OTCS URL -> %s", request_url)

        try:
            response = requests.get(
                url=request_url,
                headers=REQUEST_JSON_HEADERS,
                timeout=REQUEST_TIMEOUT,
            )
        except requests.exceptions.RequestException as exception:
            logger.debug(
                "Unable to connect to -> %s; warning -> %s",
                request_url,
                str(exception),
            )
            return False

        if not response.ok:
            logger.debug(
                "Unable to connect to -> %s; status -> %s; warning -> %s",
                request_url,
                response.status_code,
                response.text,
            )
            return False

        return True

    # end method definition

    def is_ready(self) -> bool:
        """Checks if the Content Server pod is ready to receive requests.

        Args:
            None.
        Returns:
            bool: True if pod is ready. False if pod is not yet ready.
        """

        request_url = self.config()["isReady"]

        logger.debug("Trying to retrieve OTCS URL -> %s", request_url)

        try:
            response = requests.get(
                url=request_url,
                headers=REQUEST_JSON_HEADERS,
                timeout=2,
            )
        except requests.exceptions.RequestException as exception:
            logger.debug(
                "Unable to connect to -> %s; warning -> %s",
                request_url,
                str(exception),
            )
            return False

        if not response.status_code == 200:
            logger.debug(
                "Unable to connect to -> %s; status -> %s; warning -> %s",
                request_url,
                response.status_code,
                response.text,
            )
            return False

        return True

    # end method definition

    def invalidate_authentication_ticket(self):
        """If a 401 HTTP error occurs we may want to invalidate the login ticket"""

        self._otcs_ticket = None
        self._cookie = None

    # end method definition

    def authenticate(
        self, revalidate: bool = False, wait_for_ready: bool = True
    ) -> dict | None:
        """Authenticates at Content Server and retrieve OTCS Ticket.

        Args:
            revalidate (bool, optional): determinse if a re-athentication is enforced
                                         (e.g. if session has timed out with 401 error)
                                         By default we use the OTDS ticket (if exists) for the authentication with OTCS.
                                         This switch allows the forced usage of username / password for the authentication.
            wait_for_ready (bool, optional): whether or not to wait for the OTCS service to be "ready".
                                             Default is True. If you want authentication to fail fast then set it to False.
        Returns:
            dict: Cookie information of None in case of an error.
                  Also stores cookie information in self._cookie
        """

        # Already authenticated and session still valid?
        if self._cookie and not revalidate:
            logger.debug(
                "Session still valid - return existing cookie -> %s",
                str(self._cookie),
            )
            return self._cookie

        otcs_ticket = None

        if wait_for_ready:
            logger.debug("Wait for OTCS to be ready...")
            while not self.is_ready():
                logger.debug(
                    "OTCS is not ready to receive requests yet. Waiting additional 30 seconds..."
                )
                time.sleep(30)

        request_url = self.config()["authenticationUrl"]

        if self._otds_ticket and not revalidate:
            logger.debug(
                "Requesting OTCS ticket with OTDS ticket; calling -> %s",
                request_url,
            )
            request_header = {
                "Content-Type": "application/x-www-form-urlencoded",
                "Accept": "application/json",
                "OTDSTicket": self._otds_ticket,
            }

            try:
                response = requests.get(
                    url=request_url, headers=request_header, timeout=10
                )
                if response.ok:
                    otcs_ticket = response.headers.get("OTCSTicket")

            except requests.exceptions.RequestException as exception:
                logger.warning(
                    "Unable to connect to -> %s; error -> %s",
                    request_url,
                    exception.strerror,
                )

        # Check if previous authentication was not successful.
        # Then we do the normal username + password authentication:
        if not otcs_ticket:
            logger.debug(
                "Requesting OTCS ticket with User/Password; calling -> %s",
                request_url,
            )

            response = None
            try:
                response = requests.post(
                    url=request_url,
                    data=self.credentials(),  # this includes username + password
                    headers=REQUEST_FORM_HEADERS,
                    timeout=REQUEST_TIMEOUT,
                )
            except requests.exceptions.RequestException as exception:
                logger.warning(
                    "Unable to connect to -> %s; error -> %s",
                    request_url,
                    exception.strerror,
                )
                logger.warning("OTCS service may not be ready yet.")
                return None

            if response.ok:
                authenticate_dict = self.parse_request_response(
                    response, "This can be normal during restart", False
                )
                if not authenticate_dict:
                    return None
                else:
                    otcs_ticket = authenticate_dict["ticket"]
                    logger.debug("Ticket -> %s", otcs_ticket)
            else:
                logger.error(
                    "Failed to request an OTCS ticket; error -> %s", response.text
                )
                return None

        # Store authentication ticket:
        self._cookie = {"otcsticket": otcs_ticket, "LLCookie": otcs_ticket}
        self._otcs_ticket = otcs_ticket

        return self._cookie

    # end method definition

    def reauthenticate(
        self, request_cookie: dict, thread_safe: bool = True
    ) -> dict | None:
        """Re-Authenticate after session timeout. This implementation
           supports thread-safe reauthentication, making sure not multiple
           threads reauthenticate at the same time.

        Args:
            request_cookie: the cookie used in the REST API call that
                            produced the 401 HTTP error triggering the re-authentication.
                            We use it to compare it with the current cookie to see
                            if another thread may have done the reauthentication and
                            updated the cookie already.
            thread_safe (bool, optional): If True a thread-safe implementation is done.
                                          Defaults to True.

        Returns:
            dict | None: cookie information returned by authenticate()
        """

        if not thread_safe:
            return self.authenticate(revalidate=True)

        # Lock access to session for thread-safe reads
        with self._session_lock:
            # Check if the cookie used for the REST call is still the current cookie:
            if request_cookie != self.cookie():
                # Another thread has already re-authenticated; skip re-authentication
                logger.debug(
                    "Session has already been renewed with new cookie. Skip re-authentication and return new cookie -> %s",
                    str(self.cookie()),
                )
                # return the new cookie:
                return self.cookie()

        # If the session is invalid, try to acquire the semaphore and renew it
        if self._authentication_semaphore.acquire(blocking=False):
            # Renew the session (only one thread gets here)
            logger.debug(
                "Session has expired - need to renew old request cookie -> %s",
                str(request_cookie),
            )

            try:
                # The 'with' automatically acquires and releases the lock on 'authentication_condition'
                with self._authentication_condition:
                    logger.debug("Current thread got the authentication condition...")
                    # We use the _session_lock to prevent race conditions
                    # while reading / writing the self._cookie (which is modified
                    # by the authenticate() method):
                    with self._session_lock:
                        logger.debug(
                            "Current thread got the session lock and tries to re-authenticate to get new cookie"
                        )
                        try:
                            self.authenticate(revalidate=True)
                            logger.debug(
                                "Session renewal successful, new cookie -> %s",
                                str(self.cookie()),
                            )
                            time.sleep(4)
                        except Exception as auth_error:
                            logger.error(
                                "Reauthentication failed with error -> %s",
                                str(auth_error),
                            )
                            raise
                    logger.debug("Lift session lock and notify waiting threads...")
                    # Notify all waiting threads that session is renewed:
                    self._authentication_condition.notify_all()
                    logger.warning("All waiting threads have been notified.")
            finally:
                # Ensure the semaphore is released even if an error occurs
                self._authentication_semaphore.release()
                logger.debug("Semaphore released after session renewal.")
            logger.debug("Session renewing thread continues with retry of request...")
        else:
            # Other threads wait for session renewal to complete
            logger.debug(
                "Session has expired but another thread is working on renewal - current thread waiting for re-authentication..."
            )

            with self._authentication_condition:
                logger.debug("Waiting thread got the authentication condition...")
                # IMPORTANT: Don't do a session lock here. This can produce a deadlock.
                # Reason: self._authentication_condition.wait() does not release the self._session_lock
                # but just the self._authentication_condition lock.

                # Check if session is not yet renewed (still has the old cookie used for the request)
                while request_cookie == self.cookie():
                    # This code is very unlikely to be executed as
                    # _authentication_condition and _session_lock protect
                    # the else clause from running in parallel to the if clause.
                    logger.debug("Thread is now waiting for session renewal...")
                    # Wait for notification that the session is renewed:
                    self._authentication_condition.wait()
                    logger.debug(
                        "Thread received notification, session renewal complete."
                    )
                logger.debug(
                    "Waiting thread got the new cookie -> %s.", str(self.cookie())
                )
            logger.debug(
                "Waiting thread released the authentication condition and continues with retry of request..."
            )

        return self.cookie()

    # end method definition

    def get_server_info(self) -> dict | None:
        """Get Content Server information (server info)

        Args:
            None
        Returns:
            dict: server information or None if the call fails

            Example response:
            {
                'mobile': {
                    'cs_viewer_support': False,
                    'offline_use': True
                },
                'server': {
                    'advanced_versioning': True,
                    'character_encoding': 1,
                    'current_date': '2023-09-05T17:09:41',
                    'current_locale_suffix': '_en_US',
                    'domain_access_enabled': False,
                    'enhanced_advanced_versioning': False,
                    'force_download_for_mime_types': [...],
                    'language_code': 'USA',
                    'languages': [...],
                    'metadata_languages: [...],
                    'url': 'https://otcs.dev.idea-te.eimdemo.com/cs/cs'
                    'version': '23.3'
                    ...
                },
                'sessions': {
                    'enabled': True,
                    'expire_after_last_login': False,
                    'expire_after_last_request': True,
                    'logout_url': '?func=ll.DoLogout&secureRequestToken=LUAQSY%2BJs4KnlwoVgxLtxQFYrov2XefJQM9ShyhOK93Mzp3ymCxX6IGMTtUgNvTH7AYVt%2BbWLEw%3D',
                    'session_inactivity': 7020000,
                    'session_reaction_time': 180000,
                    'session_timeout': 7200000
                },
                'viewer': {
                    'content_suite': {...}
                }
            }
        """

        request_url = self.config()["serverInfoUrl"]
        request_header = self._cookie

        logger.debug(
            "Retrieve Extended ECM server information; calling -> %s", request_url
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to retrieve Extended ECM server information",
        )

    # end method definition

    def get_server_version(self) -> str | None:
        """Get Content Server version

        Args:
            None
        Returns:
            str: server version number like 23.4
        """

        response = self.get_server_info()
        if not response:
            return None

        server_info = response.get("server")
        if not server_info:
            return None

        return server_info.get("version")

    # end method definition

    def apply_config(self, xml_file_path: str) -> dict | None:
        """Apply Content Server administration settings from XML file

        Args:
            xml_file_path (str): name + path of the XML settings file
        Returns:
            dict: Import response or None if the import fails.
                  The field response["results"]["data"]["restart"] indicates if the settings
                  require a restart of the OTCS services.
        """

        filename = os.path.basename(xml_file_path)

        if not os.path.exists(xml_file_path):
            logger.error(
                "The admin settings file -> '%s' does not exist in path -> '%s'!",
                filename,
                os.path.dirname(xml_file_path),
            )
            return None

        llconfig_file = {
            "file": (filename, open(file=xml_file_path, encoding="utf-8"), "text/xml")
        }

        request_url = self.config()["importSettingsUrl"]
        request_header = self._cookie

        logger.debug(
            "Applying admin settings from file -> '%s'; calling -> %s",
            xml_file_path,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            files=llconfig_file,
            timeout=None,
            success_message="Admin settings in file -> '{}' have been applied".format(
                xml_file_path
            ),
            failure_message="Failed to import settings file -> '{}'".format(
                xml_file_path
            ),
        )

    # end method definition

    def get_user(self, name: str, show_error: bool = False) -> dict | None:
        """Lookup Extended ECM user based on the login name.

        Args:
            name (str): name of the user (login)
            show_error (bool): treat as error if user is not found
        Returns:
            dict: User information or None if the user is not found.
            The returned information has a structure like this:

            {
                'collection':
                {
                    'paging': {...},
                    'sorting': {...}
                },
                'links':
                {
                    'data': {...}
                },
                'results': [
                    {
                        'data':
                        {
                            {
                                'birth_date': None,
                                'business_email': 'pramos@M365x61936377.onmicrosoft.com',
                                'business_fax': None,
                                'business_phone': None,
                                'cell_phone': None,
                                'deleted': False,
                                'display_language': None,
                                'first_name': 'Peter',
                                'gender': None,
                                'group_id': 8006,
                                'home_address_1': None,
                                'home_address_2': None,
                                'home_fax': None,
                                'home_phone': None,
                                'id': 8123,
                                'initials': None,
                                'last_name': 'Ramos',
                                'middle_name': None,
                                'name': 'pramos',
                                'name_formatted': 'Peter Ramos',
                                ...
                                'photo_id': 13981,
                                'photo_url': 'api/v1/members/8123/photo?v=13981.1'
                                ...
                                'type'; 0,
                                'type_name': 'User'
                                }
                        }
                    }
                ]
            }
            To access the (login) name of the first user found use ["results"][0]["data"]["properties"]["name"].
            It is easier to use the method get_result_value(response, "name", 0)
        """

        # Add query parameters (these are NOT passed via JSon body!)
        # type = 0 ==> User
        query = {"where_type": 0, "where_name": name}
        encoded_query = urllib.parse.urlencode(query, doseq=True)
        request_url = self.config()["membersUrlv2"] + "?{}".format(encoded_query)

        request_header = self.request_form_header()

        logger.debug(
            "Get user with login name -> '%s'; calling -> %s", name, request_url
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get user with login -> '{}'".format(name),
            warning_message="Couldn't find user with login -> '{}'".format(name),
            show_error=show_error,
        )

    # end method definition

    def add_user(
        self,
        name: str,
        password: str,
        first_name: str,
        last_name: str,
        email: str,
        title: str,
        base_group: int,
        privileges: list | None = None,
    ) -> dict | None:
        """Add Content Server user.

        Args:
            name (str): login name of the user
            password (str): password of the user
            first_name (str): first name of the user
            last_name (str): last name of the user
            email (str): email address of the user
            title (str): title of the user
            base_group (int): base group id of the user (e.g. department)
            privileges (list, optional): values are Login, Public Access, Content Manager,
                                         Modify Users, Modify Groups, User Admin Rights,
                                         Grant Discovery, System Admin Rights
        Returns:
            dict: User information or None if the user couldn't be created (e.g. because it exisits already).
        """

        if privileges is None:
            privileges = ["Login", "Public Access"]

        user_post_body = {
            "type": 0,
            "name": name,
            "password": password,
            "first_name": first_name,
            "last_name": last_name,
            "business_email": email,
            "title": title,
            "group_id": base_group,
            "privilege_login": ("Login" in privileges),
            "privilege_public_access": ("Public Access" in privileges),
            "privilege_content_manager": ("Content Manager" in privileges),
            "privilege_modify_users": ("Modify Users" in privileges),
            "privilege_modify_groups": ("Modify Groups" in privileges),
            "privilege_user_admin_rights": ("User Admin Rights" in privileges),
            "privilege_grant_discovery": ("Grant Discovery" in privileges),
            "privilege_system_admin_rights": ("System Admin Rights" in privileges),
        }

        request_url = self.config()["membersUrlv2"]
        request_header = self.request_form_header()

        logger.debug("Add user -> '%s'; calling -> %s", name, request_url)

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=user_post_body,
            timeout=None,
            failure_message="Failed to add user -> '{}'".format(name),
        )

    # end method definition

    def search_user(self, value: str, field: str = "where_name") -> dict | None:
        """Find a user based on search criteria.

        Args:
            value (str): field value
            field (str): user field to search with (where_name, where_first_name, where_last_name)
        Returns:
            dict: User information or None if the user couldn't be found (e.g. because it doesn't exist).

            Example response:
            {
                'collection': {
                    'paging': {...},
                    'sorting': {...}
                },
                'links': {
                    'data': {...}
                },
                'results': [
                    {
                        'data': {
                            'properties': {
                                'birth_date': None,
                                'business_email': 'dfoxhoven@M365x61936377.onmicrosoft.com',
                                'business_fax': None,
                                'business_phone': None,
                                'cell_phone': None,
                                'deleted': False,
                                'display_language': None,
                                'first_name': 'Deke',
                                'gender': None,
                                'group_id': 8005,
                                'home_address_1': None,
                                'home_address_2': None,
                                'home_fax': None,
                                'home_phone': None,
                                'id': 8562,
                                'initials': 'DF',
                                'last_name': 'Foxhoven',
                                'middle_name': None,
                                'name': 'dfoxhoven',
                                'name_formatted': 'Deke Foxhoven',
                                ...
                            }
                        }
                    }
                ]
            }
        """

        request_url = self.config()["membersUrlv2"] + "?" + field + "=" + value
        request_header = self.request_form_header()

        logger.debug(
            "Searching user by field -> %s, value -> %s; calling -> %s",
            field,
            value,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Cannot find user with field -> {}, value -> {}".format(
                field,
                value,
            ),
        )

    # end method definition

    def update_user(self, user_id: int, field: str, value: str) -> dict | None:
        """Update a defined field for a user.

        Args:
            user_id (int): ID of the user
            value (str): field value
            field (str): user field
        Returns:
            dict: User information or None if the user couldn't be updated (e.g. because it doesn't exist).
        """

        user_put_body = {field: value}

        request_url = self.config()["membersUrlv2"] + "/" + str(user_id)
        request_header = self.request_form_header()

        logger.debug(
            "Updating user with ID -> %s, field -> %s, value -> %s; calling -> %s",
            str(user_id),
            field,
            value,
            request_url,
        )
        logger.debug("User Attributes -> %s", str(user_put_body))

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data=user_put_body,
            timeout=None,
            failure_message="Failed to update user with ID -> {}".format(user_id),
        )

    # end method definition

    def get_user_profile(self) -> dict | None:
        """Update a defined field for a user profile.
           IMPORTANT: this method needs to be called by the authenticated user

        Args:
            None
        Returns:
            dict: User information or None if the user couldn't be updated
                  (e.g. because it doesn't exist).
        """

        request_url = self.config()["membersUrlv2"] + "/preferences"
        request_header = self.request_form_header()

        logger.debug(
            "Get profile (settings) for current user; calling -> %s",
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get profile of current user",
        )

    # end method definition

    def update_user_profile(
        self, field: str, value: str, config_section: str = "SmartUI"
    ) -> dict | None:
        """Update a defined field for a user profile.
           IMPORTANT: this method needs to be called by the authenticated user

        Args:
            field (str): user profile field
            value (str): new field value
            config_section (str, optional): name of the config section. Possible config_section values:
                                            * SmartUI
                                            * General
                                            * Colors
                                            * ContentIntelligence
                                            * Discussion
                                            * Follow Up
                                            * Template Workspaces
                                            * Workflow
                                            * XECMGOVSettings
                                            * CommunitySettings
                                            * RecMan
                                            * PhysObj
        Returns:
            dict: User information or None if the user couldn't be updated
                  (e.g. because it doesn't exist).
        """

        user_profile_put_body = {config_section: {field: value}}

        request_url = self.config()["membersUrlv2"] + "/preferences"
        request_header = self.request_form_header()

        logger.debug(
            "Updating profile for current user, field -> %s, value -> %s; calling -> %s",
            field,
            value,
            request_url,
        )
        logger.debug("User Attributes -> %s", str(user_profile_put_body))

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data={"body": json.dumps(user_profile_put_body)},
            timeout=None,
            failure_message="Failed to update profile of current user",
        )

    # end method definition

    def update_user_photo(self, user_id: int, photo_id: int) -> dict | None:
        """Update a user with a profile photo (which must be an existing node).

        Args:
            user_id (int): ID of the user
            photo_id (int): Node ID of the photo
        Returns:
            dict: Node information or None if photo node is not found.
        """

        update_user_put_body = {"photo_id": photo_id}

        request_url = self.config()["membersUrl"] + "/" + str(user_id)
        request_header = self.request_form_header()

        logger.debug(
            "Update user ID -> %s with photo ID -> %s; calling -> %s",
            user_id,
            photo_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data=update_user_put_body,
            timeout=None,
            failure_message="Failed to update user with ID -> {}".format(user_id),
        )

    # end method definition

    def is_proxy(self, user_name: str) -> bool:
        """Check if a user is defined as proxy of the current user.
           This method differentiates between the old (xGov) based
           implementation and the new Extended ECM platform one
           that was introduced with version 23.4.

        Args:
            user_name (str): user to test (login name)
        Returns:
            bool: True is user is proxy of current user. False if not.
        """

        version_number = self.get_server_version()
        # Split the version number by dot
        parts = version_number.split(".")
        # Take the first two parts and join them back with a dot
        stripped_version = ".".join(parts[:2])

        try:
            version_number = float(stripped_version)
        except ValueError:
            version_number = 99.99  # Set to version 99.99 for "main"

        if version_number >= 23.4:
            response = self.get_user_proxies(use_v2=True)
            if self.exist_result_item(
                response=response, key="name", value=user_name, property_name=""
            ):
                return True
            else:
                return False
        else:
            response = self.get_user_proxies(use_v2=False)
            if not response or not "proxies" in response:
                return False
            proxies = response["proxies"]

            for proxy in proxies:
                if proxy["name"] == user_name:
                    return True
            return False

    # end method definition

    def get_user_proxies(self, use_v2: bool = False) -> dict | None:
        """Get list of user proxies.
           This method needs to be called as the user the proxy is acting for.
        Args:
            None
        Returns:
            dict: Node information or None if REST call fails.
        """

        if use_v2:
            request_url = self.config()["membersUrlv2"] + "/proxies"
        else:
            request_url = self.config()["membersUrl"] + "/proxies"
        request_header = self.request_form_header()

        logger.debug("Get proxy users for current user; calling -> %s", request_url)

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get proxy users for current user",
        )

    # end method definition

    def add_user_proxy(
        self,
        proxy_user_id: int,
        from_date: str = None,
        to_date: str = None,
    ) -> dict | None:
        """Add a user as a proxy user to the current user.
           IMPORTANT: This method needs to be called as the user the proxy is acting for.
           Optional this method can be provided with a time span the proxy should be active.
           This method differentiates between the old (xGov) based
           implementation and the new Extended ECM platform one
           that was introduced with version 23.4.

           Example payload for proxy user 19340 without time span:
           {"id":2545, "from_date": None, "to_date": None}

           Example payload for proxy user 19340 with time span:
           {"id":2545, "from_date":"2023-03-15", "to_date":"2023-03-31"}

        Args:
            user_id (int): ID of the user
            from_date (str, optional): start date for proxy (format YYYY-MM-DD)
            to_date (str, optional): end date for proxy (format YYYY-MM-DD)
        Returns:
            dict: Request response or None if call fails.
        """

        version_number = self.get_server_version()
        # Split the version number by dot
        parts = version_number.split(".")
        # Take the first two parts and join them back with a dot
        stripped_version = ".".join(parts[:2])
        version_number = float(stripped_version)

        # for versions older than 23.4 we need to use
        # the legacy Extended ECM for Government Proxy
        # implementation:
        if version_number >= 23.4:
            post_dict = {}
            post_dict["id"] = proxy_user_id
            post_dict["from_date"] = from_date
            post_dict["to_date"] = to_date
            post_data = {"body": json.dumps(post_dict)}
            request_url = self.config()["membersUrlv2"] + "/proxies"
            logger.debug(
                "Assign proxy user with ID -> %s to current user; calling -> %s",
                proxy_user_id,
                request_url,
            )
        else:
            post_dict = {}
            if from_date and to_date:
                post_dict["from_date"] = from_date
                post_dict["to_date"] = to_date
            post_dict = {str(proxy_user_id): post_dict}
            post_data = {"add_proxy": json.dumps(post_dict)}
            request_url = self.config()["membersUrl"] + "/proxies"
            logger.debug(
                "Assign proxy user with ID -> %s to current user (legacy xGov); calling -> %s",
                proxy_user_id,
                request_url,
            )

        request_header = self.request_form_header()

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=post_data,
            timeout=None,
            failure_message="Failed to assign proxy user with ID -> {} to current user".format(
                proxy_user_id
            ),
        )

    # end method definition

    def add_favorite(self, node_id: int) -> dict | None:
        """Add a favorite for the current (authenticated) user.

        Args:
            node_id (int): ID of the node.
        Returns:
            dict: Request response or None if the favorite creation has failed.
        """

        request_url = self.config()["favoritesUrl"] + "/" + str(node_id)
        request_header = self.request_form_header()

        logger.debug(
            "Adding favorite for node ID -> %s; calling -> %s", node_id, request_url
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            timeout=None,
            failure_message="Failed to add favorite for node ID -> {}".format(node_id),
        )

    # end method definition

    def add_favorite_tab(self, tab_name: str, order: int) -> dict | None:
        """Add a favorite tab for the current (authenticated) user.

        Args:
            tab_name (str): Name of the new tab.
            order (int): The order of the tab.
        Returns:
            dict: Request response or None if the favorite tab creation has failed.
        """

        favorite_tab_post_body = {"name": tab_name, "order": str(order)}

        request_url = self.config()["favoritesUrl"] + "/tabs"
        request_header = self.request_form_header()

        logger.debug("Adding favorite tab -> %s; calling -> %s", tab_name, request_url)

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=favorite_tab_post_body,
            timeout=None,
            failure_message="Failed to add favorite tab -> {}".format(tab_name),
        )

    # end method definition

    def get_group(self, name: str, show_error: bool = False) -> dict | None:
        """Lookup Content Server group.

        Args:
            name (str): name of the group
            show_error (bool): if True, treat as error if group is not found
        Returns:
            dict: Group information or None if the group is not found.
            The returned information has a structure like this:
            "data": [
                {
                    "id": 0,
                    "name": "string",
                    ...
                }
            ]
            To access the id of the first group found use ["data"][0]["id"]
        """

        # Add query parameters (these are NOT passed via JSon body!)
        # type = 1 ==> Group
        query = {"where_type": 1, "where_name": name}
        encoded_query = urllib.parse.urlencode(query, doseq=True)
        request_url = self.config()["membersUrlv2"] + "?{}".format(encoded_query)

        request_header = self.request_form_header()

        logger.debug("Get group with name -> '%s'; calling -> %s", name, request_url)

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get group -> '{}'".format(name),
            warning_message="Group -> '{}' does not yet exist".format(name),
            show_error=show_error,
        )

    # end method definition

    def add_group(self, name: str) -> dict | None:
        """Add Content Server group.

        Args:
            name (str): name of the group
        Returns:
            dict: Group information or None if the group couldn't be created (e.g. because it exisits already).
        """

        group_post_body = {"type": 1, "name": name}

        request_url = self.config()["membersUrlv2"]
        request_header = self.request_form_header()

        logger.debug("Adding group -> '%s'; calling -> %s", name, request_url)
        logger.debug("Group Attributes -> %s", str(group_post_body))

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=group_post_body,
            timeout=None,
            failure_message="Failed to add group -> '{}'".format(name),
        )

    # end method definition

    def get_group_members(
        self, group: int, member_type: int, limit: int = 100
    ) -> dict | None:
        """Get Content Server group members.

        Args:
            group (int): ID of the group.
            member_type (int): users = 0, groups = 1
            limit (int, optional): max number of results (internal default is 25)
        Returns:
            dict: Group members or None if the group members couldn't be found.
        """

        # default limit is 25 which may not be enough for groups with many members
        # where_type = 1 makes sure we just get groups and not users
        request_url = (
            self.config()["membersUrlv2"]
            + "/"
            + str(group)
            + "/members?where_type="
            + str(member_type)
            + "&limit="
            + str(limit)
        )
        request_header = self.request_form_header()

        logger.debug(
            "Get members of group with ID -> %s; calling -> %s",
            str(group),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get members of group with ID -> {}".format(
                group
            ),
        )

    # end method definition

    def add_group_member(self, member_id: int, group_id: int) -> dict | None:
        """Add a user or group to a target group.

        Args:
            member_id (int): ID of the user or group to add.
            group_id (int): ID of the target group.
        Returns:
            dict: Response or None if adding a the member fails.
        """

        group_member_post_body = {"member_id": member_id}

        request_url = self.config()["membersUrlv2"] + "/" + str(group_id) + "/members"
        request_header = self.request_form_header()

        logger.debug(
            "Adding member with ID -> %s to group with ID -> %s; calling -> %s",
            str(member_id),
            str(group_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=group_member_post_body,
            timeout=None,
            failure_message="Failed to add member with ID -> {} to group with ID -> {}".format(
                member_id, group_id
            ),
        )

    # end method definition

    def get_node(
        self,
        node_id: int,
        fields: (
            str | list
        ) = "properties",  # per default we just get the most important information
        metadata: bool = False,
        timeout: int = REQUEST_TIMEOUT,
    ) -> dict | None:
        """Get a node based on the node ID.

        Args:
            node_id (int) is the node Id of the node
            fields (str | list, optional): Which fields to retrieve. This can have a big impact on performance!
                                            Possible fields:
                                            * "properties" - can further be restricted by adding sub-fields in {...} like "properties{id,name,parent_id,description}"
                                            * "categories"
                                            * "versions" - can further be restricted by adding ".element(0)" to just get the latest version
                                            * "permissions" - canfurther be restricted by adding ".limit(5)" to just get the first 5 permissions
                                            fields can either be a string (to select just one field group) or a list of strings to select multiple groups
            metadata (bool, optional): Returns metadata (data type, field length, min/max values, etc.)
                                       about data, which will be returned under results.metadata /
                                       metadata_map / metadata_order
            timeout (int, optional): timeout for the request in seconds
        Returns:
            dict: Node information or None if no node with this ID is found.

        """

        query = {}
        if fields:
            query["fields"] = fields

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "?{}".format(encoded_query)
        )

        if metadata:
            request_url += "&metadata"

        request_header = self.request_form_header()

        logger.debug("Get node with ID -> %s; calling -> %s", str(node_id), request_url)

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=timeout,
            failure_message="Failed to get node with ID -> {}".format(node_id),
        )

    # end method definition

    def get_node_by_parent_and_name(
        self,
        parent_id: int,
        name: str,
        fields: str | list = "properties",
        show_error: bool = False,
        exact_match: bool = True,
    ) -> dict | None:
        """Get a node based on the parent ID and name. This method does basically
           a query with "where_name" and the "result" is a list.

        Args:
            parent_id (int) is the node Id of the parent node
            name (str) is the name of the node to get
            fields (str | list, optional): Which fields to retrieve. This can have a big impact on performance!
                                            Possible fields:
                                            * "properties" - can further be restricted by adding sub-fields in {...} like "properties{id,name,parent_id,description}"
                                            * "categories"
                                            * "versions" - can further be restricted by adding ".element(0)" to just get the latest version
                                            * "permissions" - canfurther be restricted by adding ".limit(5)" to just get the first 5 permissions
                                            fields can either be a string (to select just one field group) or a list of strings to select multiple groups
            show_error (bool, optional): treat as error if node is not found
        Returns:
            dict: Node information or None if no node with this name is found in parent.
                        Access to node ID with: response["results"][0]["data"]["properties"]["id"]
        """

        # Add query parameters (these are NOT passed via JSon body!)
        query = {"where_name": name}
        if fields:
            query["fields"] = fields
        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(parent_id)
            + "/nodes?limit=100&{}".format(encoded_query)
        )
        request_header = self.request_form_header()

        logger.debug(
            "Get node with name -> '%s' and parent ID -> %s; calling -> %s",
            name,
            str(parent_id),
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            warning_message="Node with name -> '{}' and parent ID -> {} does not exist".format(
                name, parent_id
            ),
            failure_message="Failed to get node with name -> '{}' and parent ID -> {}".format(
                name, parent_id
            ),
            show_error=show_error,
        )

        # Filter results for exact matches only
        if exact_match:
            results = response.get("results", [])
            filtered_results = next(
                (
                    node
                    for node in results
                    if node.get("data", {}).get("properties", {}).get("name") == name
                ),
                None,
            )

            response["results"] = [] if filtered_results is None else [filtered_results]

        return response

    # end method definition

    def get_node_by_workspace_and_path(
        self,
        workspace_id: int,
        path: list,
        create_path: bool = False,
        show_error: bool = False,
    ) -> dict | None:
        """Get a node based on the workspace ID (= node ID) and path (list of folder names).

        Args:
            workspace_id (int): node ID of the workspace
            path (list): list of container items (top down), last item is name of to be retrieved item.
                         If path is empty the node of the volume is returned.
            create_path (bool): whether or not missing folders in the path should be created
            show_error (bool, optional): treat as error if node is not found
        Returns:
            dict: Node information or None if no node with this path is found.
        """

        parent_item_id = workspace_id

        # in case the path is an empty list
        # we will have the node of the workspace:
        node = self.get_node(parent_item_id)

        for path_element in path:
            node = self.get_node_by_parent_and_name(parent_item_id, path_element)
            current_item_id = self.get_result_value(node, "id")
            if not current_item_id:
                if create_path:
                    # create missing path element:
                    response = self.create_item(
                        parent_id=parent_item_id,
                        item_type=str(0),
                        item_name=path_element,
                        show_error=False,
                    )
                    # We may have a race condition here - another thread may have created the folder in parallel
                    if not response:
                        logger.warning(
                            "Cannot create folder -> '%s' in workspace with ID -> %s (path -> %s), it may already exist (race condition). Try to get it...",
                            path_element,
                            workspace_id,
                            str(path),
                        )
                        response = self.get_node_by_parent_and_name(
                            parent_id=parent_item_id,
                            name=path_element,
                            show_error=True,
                        )
                        if not response:
                            if show_error:
                                logger.error(
                                    "Cannot create path element -> %s!", path_element
                                )
                            else:
                                logger.debug(
                                    "Cannot create path element -> %s.", path_element
                                )
                            return None
                    # now we set current item ID to the new response:
                    current_item_id = self.get_result_value(response, "id")
                    node = response
                # end if create_path
                else:
                    if show_error:
                        logger.error("Cannot find path element -> %s!", path_element)
                    else:
                        logger.debug("Cannot find path element -> %s.", path_element)
                    return None
            logger.debug(
                "Traversing path element -> '%s' (%s)",
                path_element,
                str(current_item_id),
            )
            parent_item_id = current_item_id

        return node

    # end method definition

    def get_node_by_volume_and_path(
        self, volume_type: int, path: list | None = None, create_path: bool = False
    ) -> dict | None:
        """Get a node based on the volume and path (list of container items).

        Args:
            volume_type (int): Volume type ID (default is 141 = Enterprise Workspace)
                "Records Management"                = 550
                "Content Server Document Templates" = 20541
                "O365 Office Online Volume"         = 1296
                "Categories Volume"                 = 133
                "Perspectives"                      = 908
                "Perspective Assets"                = 954
                "Facets Volume"                     = 901
                "Transport Warehouse"               = 525
                "Transport Warehouse Workbench"     = 528
                "Transport Warehouse Package"       = 531
                "Event Action Center Configuration" = 898
                "Classification Volume"             = 198
                "Support Asset Volume"              = 1309
                "Physical Objects Workspace"        = 413
                "Extended ECM"                      = 882
                "Enterprise Workspace"              = 141
                "Personal Workspace"                = 142
                "Business Workspaces"               = 862
            path (list): list of container items (top down), last item is name of to be retrieved item.
                         If path is empty the node of the volume is returned.
            create_path (bool): if path elements are missing: should they be created?
        Returns:
            dict: Node information or None if no node with this path is found.
        """

        # If path is not given we use empty list to make the for loop below working in this case as well
        if path is None:
            path = []

        # Preparation: get volume IDs for Transport Warehouse (root volume and Transport Packages)
        response = self.get_volume(volume_type)
        if not response:
            logger.error("Volume type -> %s not found!", str(volume_type))
            return None

        volume_id = self.get_result_value(response, "id")
        logger.debug(
            "Volume type -> %s has node ID -> %s", str(volume_type), str(volume_id)
        )

        current_item_id = volume_id

        # in case the path is an empty list
        # we will have the node of the volume:
        node = self.get_node(current_item_id)

        for path_element in path:
            node = self.get_node_by_parent_and_name(current_item_id, path_element)
            path_item_id = self.get_result_value(node, "id")
            if not path_item_id and create_path:
                node = self.create_item(
                    parent_id=current_item_id, item_type=0, item_name=path_element
                )
                path_item_id = self.get_result_value(node, "id")
            if not path_item_id:
                logger.error(
                    "Cannot find path element -> '%s' in container with ID -> %s.",
                    path_element,
                    str(current_item_id),
                )
                return None
            current_item_id = path_item_id
            logger.debug("Traversing path element with ID -> %s", str(current_item_id))

        return node

    # end method definition

    def get_node_from_nickname(
        self, nickname: str, show_error: bool = False
    ) -> dict | None:
        """Get a node based on the nickname.

        Args:
            nickname (str): Nickname of the node.
            show_error (bool): treat as error if node is not found
        Returns:
            dict: Node information or None if no node with this nickname is found.
        """

        request_url = self.config()["nicknameUrl"] + "/" + nickname + "/nodes"
        request_header = self.request_form_header()

        logger.debug(
            "Get node with nickname -> '%s'; calling -> %s", nickname, request_url
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            warning_message="Node with nickname -> '{}' does not exist".format(
                nickname
            ),
            failure_message="Failed to get node with nickname -> '{}'".format(nickname),
            show_error=show_error,
        )

    # end method definition

    def set_node_nickname(
        self, node_id: int, nickname: str, show_error: bool = False
    ) -> dict | None:
        """Assign a nickname to an Extended ECM node (e.g. workspace)

        Args:
            nickname (str): Nickname of the node.
            show_error (bool): treat as error if node is not found
        Returns:
            dict: Node information or None if no node with this nickname is found.
        """

        if not nickname:
            return None

        nickname = nickname.replace("-", "_")
        nickname = nickname.replace(":", "_")
        nickname = nickname.replace("/", "_")
        nickname = nickname.replace(" ", "_")

        nickname_put_body = {"nickname": nickname}

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/nicknames"
        request_header = self.request_form_header()

        logger.debug(
            "Assign nickname -> '%s' to node with ID -> %s; calling -> %s",
            nickname,
            node_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data=nickname_put_body,
            timeout=None,
            warning_message="Cannot assign nickname -> '{}' to node ID -> {}. Maybe the nickname is already in use or the node does not exist.".format(
                nickname, node_id
            ),
            failure_message="Failed to assign nickname -> '{}' to node ID -> {}".format(
                nickname, node_id
            ),
            show_error=show_error,
        )

    # end method definition

    def get_subnodes(
        self,
        parent_node_id: int,
        filter_node_types: int = -2,
        filter_name: str = "",
        show_hidden: bool = False,
        limit: int = 100,
        page: int = 1,
        fields: (
            str | list
        ) = "properties",  # per default we just get the most important information
        metadata: bool = False,
    ) -> dict | None:
        """Get a subnodes of a parent node ID.

        Args:
            parent_node_id (int): Node Id of the node
            filter_node_types (int, optional):
                -1 get all containers
                -2 get all searchable objects (default)
                -3 get all non-containers
            filter_name (str, optional): filter nodes for specific name (default = no filter)
            show_hidden (bool, optional): list also hidden items (default = False)
            limit (int, optional): maximum number of results (default = 100)
            page (int, optional): number of result page (default = 1 = 1st page)
            fields (str | list, optional): Which fields to retrieve. This can have a big impact on performance!
                                            Possible fields:
                                            * "properties" - can further be restricted by adding sub-fields in {...} like "properties{id,name,parent_id,description}"
                                            * "categories"
                                            * "versions" - can further be restricted by adding ".element(0)" to just get the latest version
                                            * "permissions" - canfurther be restricted by adding ".limit(5)" to just get the first 5 permissions
                                            fields can either be a string (to select just one field group) or a list of strings to select multiple groups
            metadata (bool, optional): Returns metadata (data type, field length, min/max values, etc.)
                                       about data, which will be returned under results.metadata /
                                       metadata_map / metadata_order
        Returns:
            dict: Subnodes information or None if no node with this parent ID is found.
            Example:

            "results": [
                {
                    "data": [
                        {
                            "columns": [
                                {
                                "data_type": 0,
                                "key": "string",
                                "name": "string",
                                "sort_key": "string"
                                }
                            ],
                            "properties": [
                                {
                                    "advanced_versioning": true,
                                    "container": true,
                                    "container_size": 0,
                                    "create_date": "string",
                                    "create_user_id": 0,
                                    "description": "string",
                                    "description_multilingual": {
                                        "en": "string",
                                        "de": "string"
                                    },
                                    "external_create_date": "2019-08-24",
                                    "external_identity": "string",
                                    "external_identity_type": "string",
                                    "external_modify_date": "2019-08-24",
                                    "external_source": "string",
                                    "favorite": true,
                                    "guid": "string",
                                    "hidden": true,
                                    "icon": "string",
                                    "icon_large": "string",
                                    "id": 0,
                                    "modify_date": "2019-08-24",
                                    "modify_user_id": 0,
                                    "name": "string",
                                    "name_multilingual": {
                                        "en": "string",
                                        "de": "string"
                                    },
                                    "owner": "string",
                                    "owner_group_id": 0,
                                    "owner_user_id": 0,
                                    "parent_id": 0,
                                    "reserved": true,
                                    "reserved_date": "string",
                                    "reserved_user_id": 0,
                                    "status": 0,
                                    "type": 0,
                                    "type_name": "string",
                                    "versionable": true,
                                    "versions_control_advanced": true,
                                    "volume_id": 0
                                }
                            ]
                        }
                    ]
                }
            ]
        """

        # Add query parameters (these are NOT passed via JSon body!)
        query = {
            "where_type": filter_node_types,
            "limit": limit,
        }
        if filter_name:
            query["where_name"] = filter_name
        if show_hidden:
            query["show_hidden"] = show_hidden
        if page > 1:
            query["page"] = page
        if fields:
            query["fields"] = fields

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(parent_node_id)
            + "/nodes"
            + "?{}".format(encoded_query)
        )

        if metadata:
            request_url += "&metadata"

        request_header = self.request_form_header()

        logger.debug(
            "Get subnodes of parent node with ID -> %s; calling -> %s",
            str(parent_node_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get subnodes for parent node with ID -> {}".format(
                parent_node_id
            ),
        )

    # end method definition

    def lookup_node(
        self, parent_node_id: int, category: str, attribute: str, value: str
    ) -> dict:
        """Lookup the node under a parent node that has a specified value in a category attribute.

        Args:
            parent_node_id (int): Node ID of the parent (typically folder or workspace)
            category (str): name of the category
            attribute (str): name of the attribute that includes the value to match with
            value (str): given lookup value

        Returns:
            dict: Node or None if the REST API fails.
        """

        response = self.get_subnodes(
            parent_node_id=parent_node_id,
            limit=250,
            fields=["properties", "categories"],
            metadata=True,
        )
        if not response or not response.get("results", None):
            return None

        nodes = response["results"]
        for node in nodes:
            schema = node["metadata"]["categories"]
            data = node["data"]["categories"]
            for cat_data, cat_schema in zip(data, schema):

                data_values = list(cat_data.values())
                schema_values = list(cat_schema.values())
                # Schema has one additional element (the first one) representing
                # the category object itself. This includes the name. We need
                # to remove (pop) it from the schema list to make sure the schema list
                # and the data list have the same number of items. Otherwise
                # the following for loop with zip() would not properly align the
                # two lists:
                category_name = schema_values.pop(0)["name"]
                if category_name == category:
                    for attr_data, attr_schema in zip(data_values, schema_values):
                        attr_name = attr_schema["name"]
                        if attr_name == attribute:
                            if isinstance(attr_data, list):
                                if value in attr_data:
                                    return node
                            else:
                                if value == attr_data:
                                    return node
                    # we can break here and continue with the next node
                    # as we had the right category but did not find the matching value
                    break

        logger.warning(
            "Coudn't find a node with the value -> '%s' in the attribute -> '%s' of category -> '%s'.",
            value,
            attribute,
            category,
        )

        return None

    # end method definition

    def get_node_columns(self, node_id: int) -> dict:
        """Get custom columns configured / enabled for a node.

        Args:
            node_id (int): ID of the Node.
        Returns:
            dict: Information of the Node columns or None if the request fails.

            Example:
            {
                'links': {
                    'data': {...}
                },
                'results': {
                    'columns_to_display': {
                        'global_columns': ['Type', 'Name', 'Size', 'Modified'],
                        'inherited_columns': [
                            {
                                'id': 6270,
                                'name': 'Title',
                                'locked': False,
                                'default': False,
                                'has_permission': True,
                                'location_id': 6271,
                                'displayed': False,
                                'location_name': 'Knowledge Base Articles'
                            },
                            {
                                'id': 13076,
                                'name': 'Published Date',
                                'locked': False,
                                'default': False,
                                'has_permission': True,
                                'location_id': 6271,
                                'displayed': False,
                                'location_name': 'Knowledge Base Articles'
                            },
                            {
                                'id': 6248,
                                'name': 'Valid To Date',
                                'locked': False,
                                'default': False,
                                'has_permission': True,
                                'location_id': 6271,
                                'displayed': False,
                                'location_name': 'Knowledge Base Articles'
                            },
                            ...
                        ],
                        'local_columns': {
                            'available_columns': [
                                {
                                    'id': 13072,
                                    'name': 'Application',
                                    'default': False
                                },
                                {
                                    'id': 6288,
                                    'name': 'Approved Usage',
                                    'default': False
                                },
                                {
                                    'id': 6262,
                                    'name': 'Business Function',
                                    'default': False
                                },
                                ...
                            ],
                            'displayed_columns': [...]
                        }
                    },
                    'columns_to_sort': {
                        'inherited_sort': {
                            'column_id': None,
                            'column_name': None,
                            'sort_direction': None
                        },
                        'local_sort': {
                            'local_sort_column': [
                                {
                                    'value': 13072,
                                    'name': 'Application',
                                    'selected': False
                                },
                                {
                                    'value': 6288,
                                    'name': 'Approved Usage',
                                    'selected': False
                                },
                                ...
                            ],
                            'local_sort_order': [...]
                        }
                    }
                }
            }
        """

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/columns"

        request_header = self.request_form_header()

        logger.debug(
            "Get columns for node with ID -> %s; calling -> %s",
            str(node_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get columns for node with ID -> {}".format(
                node_id
            ),
        )

    # end method definition

    def get_node_actions(
        self, node_id: int | list, filter_actions: list = None
    ) -> dict:
        """Get allowed actions for a node.

        Args:
            node_id (int | list): ID(s) of the Node(s). This can either be int (= single node) or a list of nodes
            filter_actions (list, optional): Optional list of actions to filter for,
                                             e.g. "delete", "copy", "permissions", "makefavorite", "open", "collect", "audit", ...
        Returns:
            dict: Information of the Node actions or None if the request fails. "results" is a dictionary with Node IDs as keys,
                  and three sub-sictionaries "data", "map", and "order.

            Example:
            {
                'links': {'data': {...}},
                'results': {
                    '173301412': {
                        'data': {
                            'AddRMClassifications': {'body': '{"displayPrompt":false,"enabled":false,"inheritfrom":false,"managed":true}', 'content_type': 'application/x-www-form-urlencoded', 'form_href': '', 'href': '/api/v2/nodes/164878074/rmclassifications', 'method': 'POST', 'name': 'Add RM Classification'},
                            'audit': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074/audit?limit=1000', 'method': 'GET', 'name': 'Audit'},
                            'BrowseClassifiedItems': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074/nodes', 'method': 'GET', 'name': 'Browse classified items'},
                            'BrowseRecManContainer': {'body': '', 'content_type': 'application/x-www-form-urlencoded', 'form_href': '', 'href': '', 'method': '', 'name': ''},
                            'collect': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074', 'method': 'PUT', 'name': 'Collect'},
                            'copy': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes', 'method': 'POST', 'name': 'Copy'},
                            'makefavorite': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/members/favorites/164878074', 'method': 'POST', 'name': 'Add to Favorites'},
                            'more': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': '...'},
                            'open': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074/nodes', 'method': 'GET', 'name': 'Open'},
                            'permissions': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': 'Permissions'}, 'preview': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': 'Preview'},
                            'PrinteFile': {'body': '', 'content_type': '', 'form_href': '', 'href': 'api/v2/govprint', 'method': 'POST', 'name': 'Print'}, 'properties': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074', 'method': 'GET', 'name': 'Properties'},
                            'SendOutlookReminder': {'body': '', 'content_type': '', 'form_href': '', 'href': 'api/v2/node/xgovoutlookreminder', 'method': 'POST', 'name': 'Send Outlook reminder'},
                            'viewx-compare': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': 'viewx-compare'},
                            'viewx-transform': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': 'viewx-transform'}},
                        'map': {...},
                        'order': [...]
                    }
                }
        """

        if isinstance(node_id, list):
            actions_post_body = {"ids": node_id, "actions": filter_actions}
        else:
            actions_post_body = {"ids": [node_id], "actions": filter_actions}

        request_url = self.config()["nodesUrlv2"] + "/actions"

        request_header = self.request_form_header()

        logger.debug(
            "Get actions for node(s) with ID -> %s; calling -> %s",
            str(node_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=actions_post_body,
            timeout=None,
            failure_message="Failed to get actions for node with ID -> {}".format(
                node_id
            ),
        )

    # end method definition

    def rename_node(
        self,
        node_id: int,
        name: str,
        description: str,
        name_multilingual: dict | None = None,
        description_multilingual: dict | None = None,
    ) -> dict | None:
        """Change the name and description of a node.

        Args:
            node_id (int): ID of the node. You can use the get_volume() function below to
                               to the node id for a volume.
            name (str): New name of the node.
            description (str): New description of the node.
            name_multilingual (dict, optional): multi-lingual node names
            description_multilingual (dict, optional): multi-lingual description
        Returns:
            dict: Request response or None if the renaming fails.
        """

        rename_node_put_body = {"name": name, "description": description}

        if name_multilingual:
            rename_node_put_body["name_multilingual"] = name_multilingual
        if description_multilingual:
            rename_node_put_body["description_multilingual"] = description_multilingual

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id)
        request_header = self.request_form_header()

        logger.debug(
            "Rename node with ID -> %s to -> '%s'; calling -> %s",
            str(node_id),
            name,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data={"body": json.dumps(rename_node_put_body)},
            timeout=None,
            failure_message="Failed to rename node with ID -> {} to -> '{}'".format(
                node_id, name
            ),
        )

    # end method definition

    def delete_node(self, node_id: int, purge: bool = False) -> dict | None:
        """Delete an existing node

        Args:
            node_id (int): ID of the node to be deleted
            purge (bool, optional): If True, immediately purge the item from the recycle bin

        Returns:
            dict: response of the REST call; None in case of a failure
        """

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id)
        request_header = self.request_form_header()

        logger.debug(
            "Delete node with ID -> %s%s; calling -> %s",
            str(node_id),
            " (with immediate purging from recycle bin)" if purge else "",
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="DELETE",
            headers=request_header,
            timeout=None,
            failure_message="Failed to delete node with ID -> {}".format(node_id),
        )

        # Do we want to immediately purge it from the Recycle Bin?
        if response and purge:
            self.purge_node(node_id)

        return response

    # end method definition

    def purge_node(self, node_id: int | list):
        """Purge an item in the recycle bin (final destruction)

        Args:
            node_id (int | list): ID(s) of the node(s) to be finally deleted
        """

        request_url = self.config()["recycleBinUrl"] + "/nodes/purge"
        request_header = self.request_form_header()

        if isinstance(node_id, list):
            purge_data = {"ids": node_id}
        else:
            purge_data = {"ids": [node_id]}

        logger.debug(
            "Purge node(s) with ID(s) -> %s from recycle bin; calling -> %s",
            str(node_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=purge_data,
            timeout=None,
            failure_message="Failed to purge node with ID -> {} from the recycle bin".format(
                node_id
            ),
        )

    # end method definition

    def restore_node(self, node_id: int | list) -> dict | None:
        """Restore an item from the recycle bin (undo deletion)

        Args:
            node_id (int | list): ID(s) of the node(s) to be restored

        Results:
            dict | None: dictionary include key 'success' with the successful restored IDs

        Example:
            {
                'failure': {
                    'errors': {}, 'ids': [...]
                },
                'success': {
                    'ids': [...]
                }
            }
        """

        request_url = self.config()["recycleBinUrl"] + "/nodes/restore"
        request_header = self.request_form_header()

        if isinstance(node_id, list):
            restore_data = {"ids": node_id}
        else:
            restore_data = {"ids": [node_id]}

        logger.debug(
            "Restore node(s) with ID(s) -> %s from recycle bin; calling -> %s",
            str(node_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=restore_data,
            timeout=None,
            failure_message="Failed to restore node(s) with ID(s) -> {} from the recycle bin".format(
                node_id
            ),
        )

    # end method definition

    def get_volumes(self) -> dict | None:
        """Get all Volumes.

        Args:
            None
        Returns:
            dict: Volume Details or None if an error occured.
            {
                'links': {
                    'data': {...}
                },
                'results': [
                    {
                        'data': {
                            'properties': {
                                'advanced_versioning': None,
                                'container': True,
                                'container_size': 16,
                                'create_date': '2023-05-07T23:18:50Z',
                                'create_user_id': 1000,
                                'description': '',
                                'description_multilingual': {'de': '', 'en': '', 'fr': '', 'it': '', 'ja': ''},
                                'external_create_date': None,
                                'external_identity': '',
                                'external_identity_type': '',
                                'external_modify_date': None,
                                'external_source': '',
                                'favorite': False,
                                'hidden': False,
                                ...
                                'id': 2000,
                                ...
                                'name': 'Enterprise',
                                'name_multilingual': {'de': '', 'en': 'Enterprise', 'fr': '', 'it': '', 'ja': ''},
                                ...
                                'parent_id': -1,
                                'type': 141,
                                'volume_id': -2000,
                                ...
                            }
                            ...
                        }
                    },
                    ...
                ]
            }
            Example:
            ["results"][0]["data"]["properties"]["id"] is the node ID of the volume.
        """

        request_url = self.config()["volumeUrl"]
        request_header = self.request_form_header()

        logger.debug("Get all volumes; calling -> %s", request_url)

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get volumes",
        )

    # end method definition

    def get_volume(
        self, volume_type: int, timeout: int = REQUEST_TIMEOUT
    ) -> dict | None:
        """Get Volume information based on the volume type ID.

        Args:
            volume_type (int): ID of the volume type
            timeout (int, optional): timeout for the request in seconds
        Returns:
            dict: Volume Details or None if volume is not found.
            ["results"]["data"]["properties"]["id"] is the node ID of the volume.
        """

        request_url = self.config()["volumeUrl"] + "/" + str(volume_type)
        request_header = self.request_form_header()

        logger.debug(
            "Get volume type -> %s; calling -> %s", str(volume_type), request_url
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=timeout,
            failure_message="Failed to get volume of type -> {}".format(volume_type),
        )

    # end method definition

    def check_node_name(self, parent_id: int, node_name: str) -> dict | None:
        """Check if a node with a given name does already exist under a given parent node.

        Args:
            parent_id (int): ID of the parent location
            node_name (str): name of the new node
        Returns:
            dict | None: if response["results"] contains an element then the node with the name does exist.
                         if not response["results"] then the node with the given name does not exist
                         None in case an error occured
        """

        request_url = self.config()["validationUrl"]
        request_header = self.request_form_header()

        logger.debug(
            "Check if node with name -> '%s' can be created in parent with ID -> %s; calling -> %s",
            node_name,
            str(parent_id),
            request_url,
        )

        check_node_name_post_data = {"parent_id": parent_id, "names": [node_name]}

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data={"body": json.dumps(check_node_name_post_data)},
            timeout=None,
            failure_message="Failed to check if node name -> '{}' can be created in parent with ID -> {}".format(
                node_name, parent_id
            ),
        )

    # end method definition

    def upload_file_to_volume(
        self, package_url: str, file_name: str, mime_type: str, volume_type: int
    ) -> dict | None:
        """Fetch a file from a URL or local filesystem and upload it to a Content Server volume.

        Args:
            package_url (str): URL to download file
            file_name (str): name of the file
            mime_type (str): mimeType of the file
            volume_type (int): type (ID) of the volume
        Returns:
            dict: Upload response or None if the upload fails.
        """

        if package_url.startswith("http"):
            # Download file from remote location specified by the packageUrl
            # this must be a public place without authentication:
            logger.debug("Download transport package from URL -> %s", package_url)

            try:
                package = requests.get(url=package_url, timeout=1200)
                package.raise_for_status()
            except requests.exceptions.HTTPError as errh:
                logger.error("Http Error -> %s", errh.strerror)
                return None
            except requests.exceptions.ConnectionError as errc:
                logger.error("Error Connecting -> %s", errc.strerror)
                return None
            except requests.exceptions.Timeout as errt:
                logger.error("Timeout Error -> %s", errt.strerror)
                return None
            except requests.exceptions.RequestException as err:
                logger.error("Request error -> %s", err.strerror)
                return None

            logger.debug(
                "Successfully downloaded package -> %s; status code -> %s",
                package_url,
                package.status_code,
            )
            file = package.content

        elif os.path.exists(package_url):
            logger.debug("Using local package -> %s", package_url)
            file = open(file=package_url, mode="rb")

        else:
            logger.warning("Cannot access -> %s", package_url)
            return None

        upload_post_data = {"type": str(volume_type), "name": file_name}
        upload_post_files = [("file", (f"{file_name}", file, mime_type))]

        request_url = self.config()["nodesUrlv2"]

        # When we upload files using the 'files' parameter, the request must be encoded
        # as multipart/form-data, which allows binary data (like files) to be sent along
        # with other form data.
        # The requests library sets this header correctly if the 'files' parameter is provided.
        # So we just put the cookie in the header and trust the request library to add
        # the Content-Type = multipart/form-data :
        request_header = self.cookie()

        logger.debug(
            "Upload package -> '%s' with mime type -> '%s'; calling -> %s",
            file_name,
            mime_type,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=upload_post_data,
            files=upload_post_files,
            timeout=None,
            failure_message="Failed to upload file -> '{}' to volume of type -> {}".format(
                package_url, volume_type
            ),
        )

    # end method definition

    def upload_file_to_parent(
        self,
        file_url: str,
        file_name: str,
        mime_type: str,
        parent_id: int,
        category_data: dict | None = None,
        description: str = "",
        external_modify_date: str | None = None,
        external_create_date: str | None = None,
        show_error: bool = True,
    ) -> dict | None:
        """Fetch a file from a URL or local filesystem and upload it to a Content Server parent (folder).

        Args:
            file_url (str): URL to download file or local file
            file_name (str): name of the file
            mime_type (str): mimeType of the file
            parent_id (int): parent (ID) of the file to upload
            category_data (dict): metadata / category data
                                    Example: category ID = 12508
                                    {
                                        "12508": {
                                            "12508_2": "Draft",         # Text drop-down
                                            "12508_3": 8559,            # user ID
                                            "12508_4": "2023-05-10",    # date
                                            "12508_6": 7357,            # user ID
                                            "12508_7": "2023-05-11",    # date
                                            "12508_5": True,            # checkbox / bool
                                            "12508_8": "EN",            # text drop-down
                                            "12508_9": "MS Word",       # text drop-down
                                        }
                                    }
            description (str, optional): description of the document
            external_create_date (str, optional) value of the source system in format 2024-06-24
            external_modify_date (str, optional) value of the source system in format 2024-06-24
            show_error (bool, optional): treat as error if upload has failed
                                         (you may not want to show an error if the file already exists)
        Returns:
            dict: Upload response or None if the upload fails.
        """

        if not file_name:
            logger.error("Missing file name! Cannot upload file.")
            return None

        # Make sure we don't have leading or trailing whitespace:
        file_name = file_name.strip()

        if file_url.startswith("http"):
            # Download file from remote location specified by the file_url parameter
            # this must be a public place without authentication:
            logger.debug("Download file from URL -> %s", file_url)

            try:
                response = requests.get(url=file_url, timeout=1200)
                response.raise_for_status()
            except requests.exceptions.HTTPError as errh:
                logger.error("Http Error -> %s", errh.strerror)
                return None
            except requests.exceptions.ConnectionError as errc:
                logger.error("Error Connecting -> %s", errc.strerror)
                return None
            except requests.exceptions.Timeout as errt:
                logger.error("Timeout Error -> %s", errt.strerror)
                return None
            except requests.exceptions.RequestException as err:
                logger.error("Request error -> %s", err.strerror)
                return None

            logger.debug(
                "Successfully downloaded file -> %s; status code -> %s",
                file_url,
                response.status_code,
            )
            file_content = response.content

        elif os.path.exists(file_url):
            logger.debug("Uploading local file -> %s", file_url)
            file_content = open(file=file_url, mode="rb")

        else:
            logger.warning("Cannot access -> %s", file_url)
            return None

        upload_post_data = {
            "type": str(144),
            "name": file_name,
            "parent_id": str(parent_id),
            "external_create_date": external_create_date,
            "external_modify_date": external_modify_date,
        }

        if description:
            upload_post_data["description"] = description

        if not mime_type:
            mime_type, _ = mimetypes.guess_type(file_url)

        if not mime_type and magic_installed:
            try:
                mime = magic.Magic(mime=True)
                mime_type = mime.from_file(file_url)
            except Exception:
                logger.error(
                    "Mime type for document -> '%s' could not be identified for parent ID -> %s",
                    file_name,
                    str(parent_id),
                )

        upload_post_files = [("file", (f"{file_name}", file_content, mime_type))]

        request_url = self.config()["nodesUrlv2"]

        # When we upload files using the 'files' parameter, the request must be encoded
        # as multipart/form-data, which allows binary data (like files) to be sent along
        # with other form data.
        # The requests library sets this header correctly fwhen the 'files' parameter is provided.
        # So we just put the cookie in the header and trust the request library to add
        # the Content-Type = multipart/form-data :
        request_header = self.cookie()

        logger.debug(
            "Upload file -> '%s' with mime type -> '%s' to parent with ID -> %s; calling -> %s",
            file_name,
            mime_type,
            str(parent_id),
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=upload_post_data,
            files=upload_post_files,
            timeout=None,
            warning_message="Cannot upload file -> '{}' to parent with ID -> {}. It may already exist.".format(
                file_url, parent_id
            ),
            failure_message="Failed to upload file -> '{}' to parent -> {}".format(
                file_url, parent_id
            ),
            show_error=show_error,
        )

        node_id = self.get_result_value(response, "id")
        if not node_id:
            logger.error("No Node ID found! Cannot set category.")
            return None

        # Update the categories on the documents
        if category_data is not None:
            for category in category_data:
                self.set_category_values(
                    node_id=node_id,
                    category_id=category,
                    category_data=category_data[category],
                )

        return response

    # end method definition

    def add_document_version(
        self,
        node_id: int,
        file_url: str,
        file_name: str,
        mime_type: str = "text/plain",
        description: str = "",
    ) -> dict | None:
        """Fetch a file from a URL or local filesystem and upload it as a new document version.

        Args:
            node_id (int): ID of the document to add add version to
            file_url (str): URL to download file or local file
            file_name (str): name of the file
            mime_type (str, optional): mimeType of the file (default = text/plain)
            description (str, optional): description of the version (default = no description)
        Returns:
            dict: Add version response or None if the upload fails.
        """

        # Desciption of a version cannot be longer than 255 characters in OTCS:
        if description and len(description) > 255:
            description = description[:255]

        if file_url.startswith("http"):
            # Download file from remote location specified by the file_url parameter
            # this must be a public place without authentication:
            logger.debug("Download file from URL -> %s", file_url)

            try:
                response = requests.get(
                    url=file_url,
                    timeout=None,
                )
                response.raise_for_status()
            except requests.exceptions.HTTPError as errh:
                logger.error("Http Error -> %s", errh.strerror)
                return None
            except requests.exceptions.ConnectionError as errc:
                logger.error("Error Connecting -> %s", errc.strerror)
                return None
            except requests.exceptions.Timeout as errt:
                logger.error("Timeout Error -> %s", errt.strerror)
                return None
            except requests.exceptions.RequestException as err:
                logger.error("Request error -> %s", err.strerror)
                return None

            logger.debug(
                "Successfully downloaded file -> %s; status code -> %s",
                file_url,
                response.status_code,
            )
            file_content = response.content

        elif os.path.exists(file_url):
            logger.debug("Upload local file -> %s", file_url)
            file_content = open(file=file_url, mode="rb")

        else:
            logger.warning("Cannot access -> %s", file_url)
            return None

        upload_post_data = {"description": description}
        upload_post_files = [("file", (f"{file_name}", file_content, mime_type))]

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/versions"

        # When we upload files using the 'files' parameter, the request must be encoded
        # as multipart/form-data, which allows binary data (like files) to be sent along
        # with other form data.
        # The requests library sets this header correctly if the 'files' parameter is provided.
        # So we just put the cookie in the header and trust the request library to add
        # the Content-Type = multipart/form-data :
        request_header = self.cookie()

        logger.debug(
            "Upload file -> '%s' with mime type -> '%s' as new version to document node with ID -> %s; calling -> %s",
            file_name,
            mime_type,
            node_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=upload_post_data,
            files=upload_post_files,
            timeout=None,
            failure_message="Failed to add file -> '{}' as new version to document with ID -> {}".format(
                file_url, node_id
            ),
        )

    # end method definition

    def get_latest_document_version(self, node_id: int) -> dict | None:
        """Get latest version of a document node based on the node ID.

        Args:
            node_id (int) is the node Id of the node
        Returns:
            dict: Node information or None if no node with this ID is found.
        """

        request_url = (
            self.config()["nodesUrl"] + "/" + str(node_id) + "/versions/latest"
        )
        request_header = self.request_form_header()

        logger.debug(
            "Get latest version of document with node ID -> %s; calling -> %s",
            str(node_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get latest version of document with node ID -> {}".format(
                str(node_id)
            ),
        )

    # end method definition

    def get_document_content(
        self,
        node_id: int,
        version_number: str = "",
        parse_request_response: bool = False,
    ) -> bytes | dict | None:
        """Get document content from Extended ECM.

        Args:
            node_id (int): node ID of the document to download
            version_number (str, optional): version of the document to download.
                                            If version = "" then download the latest
                                            version.
        Returns:
            bytes | dict | None: content of the file or None in case of an error.
                                 If parse_request_response is True then then the
                                 content is interpreted as JSON and delivered as a dictionary
        """

        if not version_number:
            response = self.get_latest_document_version(node_id)
            if not response:
                logger.error(
                    "Cannot get latest version of document with ID -> %s", str(node_id)
                )
            version_number = response["data"]["version_number"]

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "/versions/"
            + str(version_number)
            + "/content"
        )
        request_header = self.request_download_header()

        logger.debug(
            "Get document with node ID -> %s and version -> %s; calling -> %s",
            str(node_id),
            str(version_number),
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to download document with node ID -> {}".format(
                node_id
            ),
            parse_request_response=parse_request_response,
        )

        if parse_request_response:
            # In this case response.content has been interpreted as JSON
            # and delivered as a Python dict (or None in case of an error):
            return response

        if response is not None:
            # In sthis case the unparsed content is delivered as bytes:
            return response.content

        return None

    # end method definition

    def get_json_document(
        self, node_id: int, version_number: str = ""
    ) -> list | dict | None:
        """Get document content from Extended ECM and read content as JSON.

        Args:
            node_id (int): node ID of the document to download
            version_number (str, optional): version of the document to download.
                                            If version = "" then download the latest
                                            version.
        Returns:
            list|dict: content of the file or None in case of an error.
        """

        return self.get_document_content(
            node_id=node_id, version_number=version_number, parse_request_response=True
        )

    # end method definition

    def download_document(
        self, node_id: int, file_path: str, version_number: str = ""
    ) -> bool:
        """Download a document from Extended ECM to local file system.

        Args:
            node_id (int): node ID of the document to download
            file_path (str): local file path (directory)
            version_number (str): version of the document to download.
                                     If version = "" then download the latest
                                     version.
        Returns:
            bool: True if the document has been download to the specified file.
                     False otherwise.
        """

        if not version_number:
            response = self.get_latest_document_version(node_id)
            if not response:
                logger.error(
                    "Cannot get latest version of document with ID -> %s", str(node_id)
                )
                return False
            version_number = response["data"]["version_number"]

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "/versions/"
            + str(version_number)
            + "/content"
        )
        request_header = self.request_download_header()

        logger.debug(
            "Download document with node ID -> %s; calling -> %s",
            str(node_id),
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to download document with node ID -> {}".format(
                node_id
            ),
            parse_request_response=False,
        )

        if response is None:
            return False

        directory = os.path.dirname(file_path)
        if not os.path.exists(directory):
            logger.warning("Directory -> '%s' does not exist, creating it.", directory)
            os.makedirs(directory)

        try:
            with open(file_path, "wb") as file:
                file.write(response.content)
        except Exception as exc:
            logger.error("Error while writing file content -> %s", exc)
            return False

        return True

    # end method definition

    def download_config_file(
        self, otcs_url_suffix: str, file_path: str, search: str = "", replace: str = ""
    ) -> bool:
        """Download a config file from a given OTCS URL. This is NOT
            for downloading documents from within the OTCS repository
            but for configuration files such as app packages for MS Teams.

        Args:
            otcs_url_suffix (str): OTCS URL suffix starting typically starting
                                      with /cs/cs?func=,
                                      e.g. /cs/cs?func=officegroups.DownloadTeamsPackage
            file_path (str): local path to save the file (direcotry + filename)
            search (str, optional): optional string to search for a replacement
            replace (str, optional): optional replacement
        Returns:
            bool: True if the download succeeds, False otherwise
        """

        request_url = self.config()["baseUrl"] + otcs_url_suffix
        request_header = self.request_download_header()

        logger.debug("Download config file from URL -> %s", request_url)

        try:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=REQUEST_TIMEOUT,
            )
            response.raise_for_status()
        except requests.exceptions.HTTPError as errh:
            logger.error("Http Error -> %s", errh.strerror)
            return False
        except requests.exceptions.ConnectionError as errc:
            logger.error("Error Connecting -> %s", errc.strerror)
            return False
        except requests.exceptions.Timeout as errt:
            logger.error("Timeout Error -> %s", errt.strerror)
            return False
        except requests.exceptions.RequestException as err:
            logger.error("Request error -> %s", err.strerror)
            return False

        content = response.content

        if search:
            logger.debug(
                "Search for all occurances of '%s' in the config file and replace them with '%s'",
                search,
                replace,
            )
            content = content.replace(search.encode("utf-8"), replace.encode("utf-8"))

        # Open file in write binary mode
        with open(file=file_path, mode="wb") as file:
            # Write the content to the file
            file.write(content)

        logger.debug(
            "Successfully downloaded config file -> %s to -> '%s'; status code -> %s",
            request_url,
            file_path,
            response.status_code,
        )

        return True

    # end method definition

    def search(
        self,
        search_term: str,
        look_for: str = "complexQuery",
        modifier: str = "",
        slice_id: int = 0,
        query_id: int = 0,
        template_id: int = 0,
        limit: int = 100,
        page: int = 1,
    ) -> dict | None:
        """Search for a search term.

        Args:
            search_term (str), e.g. "test or OTSubType: 189"
            look_for (str, optional): 'allwords', 'anywords', 'exactphrase', and 'complexquery'.
                                      If not specified, it defaults to 'complexQuery'.
            modifier (str, optional): 'synonymsof', 'relatedto', 'soundslike', 'wordbeginswith',
                                      and 'wordendswith'.
                                      If not specified or specify any value other than the available options,
                                      it will be ignored.
            slice_id (int, optional): ID of an existing search slice
            query_id (int, optional): ID of an saved search query
            template_id (int, optional): ID of an saved search template
            limit (int, optional): maximum number of results (default = 100)
            page (int, optional): number of result page (default = 1 = 1st page)
        Returns:
            dict: search response or None if the search fails.
        """

        search_post_body = {
            "where": search_term,
            "lookfor": look_for,
            "page": page,
            "limit": limit,
        }

        if modifier:
            search_post_body["modifier"] = modifier
        if slice_id > 0:
            search_post_body["slice_id"] = slice_id
        if query_id > 0:
            search_post_body["query_id"] = query_id
        if template_id > 0:
            search_post_body["template_id"] = template_id

        request_url = self.config()["searchUrl"]
        request_header = self.request_form_header()

        logger.debug("Search for term -> %s; calling -> %s", search_term, request_url)

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=search_post_body,
            timeout=None,
            failure_message="Failed to search for term -> '{}'".format(search_term),
        )

    # end method definition

    def get_external_system_connection(
        self, connection_name: str, show_error: bool = False
    ) -> dict | None:
        """Get Extended ECM external system connection (e.g. SAP, Salesforce, SuccessFactors).

        Args:
            connection_name (str): Name of the connection
            show_error (bool, optional): If True, treat as error if connection is not found.
        Returns:
            dict: External system Details or None if the REST call fails.
        """
        # Encode special characters in connection_name
        connection_name = connection_name.replace("\\", "0xF0A6").replace("/", "0xF0A7")
        request_url = (
            self.config()["externalSystemUrl"] + "/" + connection_name + "/config"
        )
        request_header = self.cookie()

        logger.debug(
            "Get external system connection -> %s; calling -> %s",
            connection_name,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            warning_message="External system connection -> '{}' does not yet exist".format(
                connection_name
            ),
            failure_message="Failed to get external system connection -> '{}'".format(
                connection_name
            ),
            show_error=show_error,
        )

    # end method definition

    def add_external_system_connection(
        self,
        connection_name: str,
        connection_type: str,
        as_url: str,
        base_url: str,
        username: str,
        password: str,
        authentication_method: str = "BASIC",  # either BASIC or OAUTH
        client_id: str = None,
        client_secret: str = None,
    ) -> dict | None:
        """Add Extended ECM external system connection (e.g. SAP, Salesforce, SuccessFactors).

        Args:
            connection_name (str): Name of the connection
            connection_type (str): Type of the connection (HTTP, SF, SFInstance)
            as_url (str): Application URL of the external system
            base_url (str): Base URL of the external system
            username (str): username (used for BASIC authentication)
            password (str): password (used for BASIC authentication)
            authentication_method (str, optional): either BASIC (using username and password) or OAUTH
            client_id (str, optional): OAUTH Client ID (only required if authenticationMethod = OAUTH)
            client_secret (str, optional): OAUTH Client Secret (only required if authenticationMethod = OAUTH)
        Returns:
            dict: External system Details or None if the REST call fails.
        """

        external_system_post_body = {
            "external_system_name": connection_name,
            "conn_type": connection_type,
            "asurl": as_url,
            "baseurl": base_url,
            "username": username,
            "password": password,
        }

        if authentication_method == "OAUTH" and client_id and client_secret:
            external_system_post_body["authentication_method"] = str(
                authentication_method
            )
            external_system_post_body["client_id"] = str(client_id)
            external_system_post_body["client_secret"] = str(client_secret)

        request_url = self.config()["externalSystemUrl"]
        request_header = self.cookie()

        logger.debug(
            "Create external system connection -> '%s' of type -> '%s' with URL -> %s; calling -> %s",
            connection_name,
            connection_type,
            as_url,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=external_system_post_body,
            timeout=None,
            failure_message="Failed to create external system connection -> '{}'".format(
                connection_name
            ),
        )

    # end method definition

    def create_transport_workbench(self, workbench_name: str) -> dict | None:
        """Create a Workbench in the Transport Volume.

        Args:
            workbench_name (str): Name of the workbench to be created
        Returns:
            dict: Create response or None if the creation fails.
        """

        create_worbench_post_data = {"type": "528", "name": workbench_name}

        request_url = self.config()["nodesUrlv2"]
        request_header = self.request_form_header()

        logger.debug(
            "Create transport workbench -> %s; calling -> %s",
            workbench_name,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=create_worbench_post_data,
            timeout=None,
            failure_message="Failed to create transport workbench -> {}".format(
                workbench_name
            ),
        )

    # end method definition

    def unpack_transport_package(
        self, package_id: int, workbench_id: int
    ) -> dict | None:
        """Unpack an existing Transport Package into an existing Workbench.

        Args:
            package_id (int): ID of package to be unpacked
            workbench_id (int): ID of target workbench
        Returns:
            dict: Unpack response or None if the unpacking fails.
        """

        unpack_package_post_data = {"workbench_id": workbench_id}

        request_url = self.config()["nodesUrlv2"] + "/" + str(package_id) + "/unpack"
        request_header = self.request_form_header()

        logger.debug(
            "Unpack transport package with ID -> %s into workbench with ID -> %s; calling -> %s",
            str(package_id),
            str(workbench_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=unpack_package_post_data,
            timeout=None,
            failure_message="Failed to unpack package with ID -> {} to workbench with ID -> {}".format(
                package_id, workbench_id
            ),
        )

    # end method definition

    def deploy_workbench(self, workbench_id: int) -> dict | None:
        """Deploy an existing Workbench.

        Args:
            workbench_d (int): ID of the workbench to be deployed
        Returns:
            dict: Deploy response or None if the deployment fails.
        """

        request_url = self.config()["nodesUrlv2"] + "/" + str(workbench_id) + "/deploy"
        request_header = self.request_form_header()

        logger.debug(
            "Deploy workbench with ID -> %s; calling -> %s",
            str(workbench_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            timeout=None,
            failure_message="Failed to deploy workbench with ID -> {}".format(
                workbench_id
            ),
        )

    # end method definition

    def deploy_transport(
        self,
        package_url: str,
        package_name: str,
        package_description: str = "",
        replacements: list | None = None,
        extractions: list | None = None,
    ) -> dict | None:
        """Main method to deploy a transport. This uses subfunctions to upload,
           unpackage and deploy the transport, and creates the required workbench.

        Args:
            package_url (str): URL to download the transport package.
            package_name (str): Name of the transport package ZIP file
            package_description (str): Description of the transport package
            replacements (list of dicts): List of replacement values to be applied
                                          to all XML files in transport;
                                          each dict needs to have two values:
                                          - placeholder: text to replace
                                          - value: text to replace with
            extractions (list of dicts): List of XML Subtrees to extract
                                         each XML file in transport;
                                         each dict needs to have two values:
                                          - xpath: defining the subtree to extract
                                          - enabled: True if the extraction is active
        Returns:
            dict: Deploy response or None if the deployment fails.
        """

        if replacements is None:
            replacements = []
        if extractions is None:
            extractions = []

        # Preparation: get volume IDs for Transport Warehouse (root volume and Transport Packages)
        response = self.get_volume(525)
        transport_root_volume_id = self.get_result_value(response, "id")
        if not transport_root_volume_id:
            logger.error("Failed to retrieve transport root volume")
            return None
        logger.debug("Transport root volume ID -> %s", str(transport_root_volume_id))

        response = self.get_node_by_parent_and_name(
            transport_root_volume_id, "Transport Packages"
        )
        transport_package_volume_id = self.get_result_value(response, "id")
        if not transport_package_volume_id:
            logger.error("Failed to retrieve transport package volume")
            return None
        logger.debug(
            "Transport package volume ID -> %s", str(transport_package_volume_id)
        )

        # Step 1: Upload Transport Package
        logger.debug(
            "Check if transport package -> '%s' already exists...", package_name
        )
        response = self.get_node_by_parent_and_name(
            transport_package_volume_id, package_name
        )
        package_id = self.get_result_value(response, "id")
        if package_id:
            logger.debug(
                "Transport package -> '%s' does already exist; existing package ID -> %s",
                package_name,
                str(package_id),
            )
        else:
            logger.debug(
                "Transport package -> '%s' does not yet exist, loading from -> %s",
                package_name,
                package_url,
            )
            # If we have string replacements configured execute them now:
            if replacements:
                logger.debug(
                    "Transport -> '%s' has replacements -> %s",
                    package_name,
                    str(replacements),
                )
                self.replace_transport_placeholders(package_url, replacements)
            else:
                logger.debug("Transport -> '%s' has no replacements!", package_name)
            # If we have data extractions configured execute them now:
            if extractions:
                logger.debug(
                    "Transport -> '%s' has extractions -> %s",
                    package_name,
                    str(extractions),
                )
                self.extract_transport_data(package_url, extractions)
            else:
                logger.debug("Transport -> '%s' has no extractions!", package_name)
            # Upload package to Extended ECM:
            response = self.upload_file_to_volume(
                package_url, package_name, "application/zip", 531
            )
            package_id = self.get_result_value(response, "id")
            if not package_id:
                logger.error("Failed to upload transport package -> %s", package_url)
                return None
            logger.debug(
                "Successfully uploaded transport package -> '%s'; new package ID -> %s",
                package_name,
                str(package_id),
            )

        # Step 2: Create Transport Workbench (if not yet exist)
        workbench_name = package_name.split(".")[0]
        logger.debug(
            "Check if workbench -> '%s' is already deployed...", workbench_name
        )
        # check if the package name has the suffix "(deployed)" - this indicates it is alreadey
        # successfully deployed (see renaming at the end of this method)
        response = self.get_node_by_parent_and_name(
            transport_root_volume_id, workbench_name + " (deployed)"
        )
        workbench_id = self.get_result_value(response, "id")
        if workbench_id:
            logger.debug(
                "Workbench -> '%s' has already been deployed successfully; existing workbench ID -> %s; skipping transport",
                workbench_name,
                str(workbench_id),
            )
            # we return and skip this transport...
            return response
        else:
            logger.debug("Check if workbench -> '%s' already exists...", workbench_name)
            response = self.get_node_by_parent_and_name(
                transport_root_volume_id, workbench_name
            )
            workbench_id = self.get_result_value(response, "id")
            if workbench_id:
                logger.debug(
                    "Workbench -> '%s' does already exist but is not successfully deployed; existing workbench ID -> %s",
                    workbench_name,
                    str(workbench_id),
                )
            else:
                response = self.create_transport_workbench(workbench_name)
                workbench_id = self.get_result_value(response, "id")
                if not workbench_id:
                    logger.error("Failed to create workbench -> '%s'", workbench_name)
                    return None
                logger.debug(
                    "Successfully created workbench -> '%s'; new workbench ID -> %s",
                    workbench_name,
                    str(workbench_id),
                )

        # Step 3: Unpack Transport Package to Workbench
        logger.debug(
            "Unpack transport package -> '%s' (%s) to workbench -> '%s' (%s)",
            package_name,
            str(package_id),
            workbench_name,
            str(workbench_id),
        )
        response = self.unpack_transport_package(package_id, workbench_id)
        if not response:
            logger.error("Failed to unpack the transport package -> '%s'", package_name)
            return None
        logger.debug(
            "Successfully unpackaged to workbench -> '%s' (%s)",
            workbench_name,
            str(workbench_id),
        )

        # Step 4: Deploy Workbench
        logger.debug("Deploy workbench -> '%s' (%s)", workbench_name, str(workbench_id))
        response = self.deploy_workbench(workbench_id)
        if not response:
            logger.error("Failed to deploy workbench -> '%s'", workbench_name)
            return None

        logger.debug(
            "Successfully deployed workbench -> '%s' (%s)",
            workbench_name,
            str(workbench_id),
        )
        self.rename_node(
            workbench_id,
            workbench_name + " (deployed)",
            package_description,
        )

        return response

    # end method definition

    def replace_transport_placeholders(
        self, zip_file_path: str, replacements: list
    ) -> bool:
        """Search and replace strings in the XML files of the transport package

        Args:
            zip_file_path (str): Path to transport zip file
            replacements (list of dicts): List of replacement values; dict needs to have two values:
                                         * placeholder: text to replace
                                         * value: text to replace with
        Returns:
            Filename to the updated zip file
        """

        if not os.path.isfile(zip_file_path):
            logger.error("Zip file -> '%s' not found.", zip_file_path)
            return False

        # Extract the zip file to a temporary directory
        zip_file_folder = os.path.splitext(zip_file_path)[0]
        with zipfile.ZipFile(zip_file_path, "r") as zfile:
            zfile.extractall(zip_file_folder)

        modified = False

        # Replace search pattern with replace string in all XML files in the directory and its subdirectories
        for replacement in replacements:
            if not "value" in replacement:
                logger.error(
                    "Replacement needs a value but it is not specified. Skipping..."
                )
                continue
            if "enabled" in replacement and not replacement["enabled"]:
                logger.debug(
                    "Replacement for transport -> '%s' is disabled. Skipping...",
                    zip_file_path,
                )
                continue
            # there are two types of replacements:
            # 1. XPath - more elegant and powerful
            # 2. Search & Replace - basically treat the XML file like a text file and do a search & replace
            if "xpath" in replacement:
                logger.debug(
                    "Using xpath -> %s to narrow down the replacement",
                    replacement["xpath"],
                )
                if "setting" in replacement:
                    logger.debug(
                        "Looking up setting -> %s in XML element",
                        replacement["setting"],
                    )
                if "assoc_elem" in replacement:
                    logger.debug(
                        "Looking up assoc element -> %s in XML element",
                        replacement["assoc_elem"],
                    )
            else:  # we have a simple "search & replace" replacement
                if not "placeholder" in replacement:
                    logger.error(
                        "Replacement without an xpath needs a placeholder value but it is not specified. Skipping..."
                    )
                    continue
                if replacement.get("placeholder") == replacement["value"]:
                    logger.debug(
                        "Placeholder and replacement are identical -> %s. Skipping...",
                        replacement["value"],
                    )
                    continue
                logger.debug(
                    "Replace -> %s with -> %s in Transport package -> %s",
                    replacement["placeholder"],
                    replacement["value"],
                    zip_file_folder,
                )

            found = XML.replace_in_xml_files(
                zip_file_folder,
                replacement.get("placeholder"),
                replacement["value"],
                replacement.get("xpath"),
                replacement.get("setting"),
                replacement.get("assoc_elem"),
            )
            if found:
                logger.debug(
                    "Replacement -> %s has been completed successfully for Transport package -> %s",
                    replacement,
                    zip_file_folder,
                )
                modified = True
            else:
                logger.warning(
                    "Replacement -> %s not found in Transport package -> %s",
                    replacement,
                    zip_file_folder,
                )

        if not modified:
            logger.warning(
                "None of the specified replacements have been found in Transport package -> %s. No need to create a new transport package.",
                zip_file_folder,
            )
            return False

        # Create the new zip file and add all files from the directory to it
        new_zip_file_path = (
            os.path.dirname(zip_file_path) + "/new_" + os.path.basename(zip_file_path)
        )
        logger.debug(
            "Content of transport -> '%s' has been modified - repacking to new zip file -> %s",
            zip_file_folder,
            new_zip_file_path,
        )
        with zipfile.ZipFile(new_zip_file_path, "w", zipfile.ZIP_DEFLATED) as zip_ref:
            for subdir, _, files in os.walk(
                zip_file_folder
            ):  # 2nd parameter is not used, thus using _ instead of dirs
                for file in files:
                    file_path = os.path.join(subdir, file)
                    rel_path = os.path.relpath(file_path, zip_file_folder)
                    zip_ref.write(file_path, arcname=rel_path)

        # Close the new zip file and delete the temporary directory
        zip_ref.close()
        old_zip_file_path = (
            os.path.dirname(zip_file_path) + "/old_" + os.path.basename(zip_file_path)
        )
        logger.debug(
            "Rename orginal transport zip file -> '%s' to -> '%s'",
            zip_file_path,
            old_zip_file_path,
        )
        os.rename(zip_file_path, old_zip_file_path)
        logger.debug(
            "Rename new transport zip file -> '%s' to -> '%s'",
            new_zip_file_path,
            zip_file_path,
        )
        os.rename(new_zip_file_path, zip_file_path)

        # Return the path to the new zip file
        return True

    # end method definition

    def extract_transport_data(self, zip_file_path: str, extractions: list) -> bool:
        """Search and extract XML data from the transport package

        Args:
            zip_file_path (str): Path to transport zip file
            extractions (list of dicts): List of extraction values; dict needs to have two values:
                                         * xpath: structure to find
                                         * enabed (optional): if the extraction is active
        Returns:
            True if successful, False otherwise. THIS METHOD MODIFIES EXTRACTIONS
            BY ADDING A NEW KEY "data" TO EACH EXTRACTION ELEMENT!!
        """

        if not os.path.isfile(zip_file_path):
            logger.error("Zip file -> '%s' not found.", zip_file_path)
            return False

        # Extract the zip file to a temporary directory
        zip_file_folder = os.path.splitext(zip_file_path)[0]
        with zipfile.ZipFile(zip_file_path, "r") as zfile:
            zfile.extractall(zip_file_folder)

        # Extract data from all XML files in the directory and its subdirectories
        for extraction in extractions:
            if not "xpath" in extraction:
                logger.error(
                    "Extraction needs an XPath but it is not specified. Skipping..."
                )
                continue
            if "enabled" in extraction and not extraction["enabled"]:
                logger.debug(
                    "Extraction for transport -> '%s' is disabled. Skipping...",
                    zip_file_path,
                )
                continue

            xpath = extraction["xpath"]
            logger.debug(
                "Using xpath -> %s to extract the data",
                xpath,
            )

            # This delivers a list of strings containing the extracted data:
            extracted_data = XML.extract_from_xml_files(
                zip_file_folder,
                xpath,
            )
            if extracted_data:
                logger.debug(
                    "Extraction with XPath -> %s has been successfully completed for Transport package -> %s",
                    xpath,
                    zip_file_folder,
                )
                # Add the extracted elements to the extraction data structure (dict).
                extraction["data"] = extracted_data
            else:
                logger.warning(
                    "Extraction with XPath -> %s has not delivered any data for Transport package -> %s",
                    xpath,
                    zip_file_folder,
                )
                extraction["data"] = []

        # Return the path to the new zip file
        return True

    # end method definition

    def get_business_object_types(self) -> dict | None:
        """Get information for all configured business object types.

        Args:
            None
        Returns:
            dict: Workspace Types information (for all external systems)
                  or None if the request fails.
        """

        request_url = self.config()["businessObjectTypesUrl"]
        request_header = self.request_form_header()

        logger.debug(
            "Get all business object types; calling -> %s",
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get business object types",
        )

    # end method definition

    def get_business_object_type(
        self,
        external_system_id: str,
        type_name: str,
        expand_workspace_type: bool = True,
        expand_external_system: bool = True,
    ) -> dict | None:
        """Get business object type information. Unfortunately this REST API is
           pretty much limited. It does not return Field names of external system properties
           and also does not return property groups defined.

        Args:
            external_system_id (str): External system Id (such as "TM6")
            type_name (str): Type name of the business object (such as "SAP Customer")
        Returns:
            dict: Business Object Type information or None if the request fails.

            Example response:
            {
                'businessProperties': [
                    {
                        'attributeID': '14012_29',
                        'categoryID': '14012',
                        'name': 'Name',
                        'type': 'String'
                    },
                    {
                        'attributeID': '14012_28',
                        'categoryID': '14012',
                        'name': 'Customer Number',
                        'type': 'String'
                    }
                ]
                'bwsinfo': {'id': None},
                'cadxref_doc_info': {'has_relation': False},
                'categories': [],
                'claimed_doc_info': {'is_claimed': False},
                'columns': [{...}, {...}, {...}, {...}],
                'doctemplates_info': {'isInDocTemplateVolTree': False},
                'followups': [],
                'nicknames': {'nickname': '16568'},
                'properties': {
                    'advanced_versioning': None,
                    'container': False,
                    'container_size': 0,
                    'create_date': '2017-11-23T16:43:34Z',
                    'create_user_id': 1000,
                    'description': '',
                    'description_multilingual': {...},
                    'external_create_date': None,
                    'external_identity': '',
                    ...
                },
                'rmiconsdata': {'class_id': 0, 'official': 0, 'show_classify': False, 'show_hold': False, 'show_hold_tab': False, 'show_label_tab': True, 'show_official': False, 'show_xref': False, 'show_xref_tab': False},
                'sestatus_doc_info': {'is_se_document': False, 'sync_tooltip': ''},
                'sharing_info': {'is_shared': False, 'sync_state': -1},
                'showmainruleicon': False,
                ...
            }
        """

        query = {
            "expand_ext_system": expand_external_system,
            "expand_wksp_type": expand_workspace_type,
        }

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        encoded_type_name = type_name.replace("/", "%2F")

        request_url = (
            self.config()["externalSystemUrl"]
            + "/"
            + external_system_id
            + "/botypes/"
            + encoded_type_name
            + "?{}".format(encoded_query)
        )
        request_header = self.request_form_header()

        logger.debug(
            "Get business object type -> '%s' for external system -> %s; calling -> %s",
            type_name,
            external_system_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get business object type -> '{}' for external system -> {}".format(
                type_name, external_system_id
            ),
        )

    # end method definition

    def get_business_objects(
        self,
        external_system_id: str,
        type_name: str,
        where_clauses: dict | None = None,
        limit: int | None = None,
        page: int | None = None,
    ) -> dict | None:
        """Get all business objects for an external system and a given business object type.

        Args:
            external_system_id (str): External system Id (such as "TM6")
            type_name (str): Type name of the business object (such as "SAP Customer")
            where_clause (dict, optional): filter the results based on 1 or kultiple
                                           where clauses (THE  NAME CONVENTION FOR THE
                                           FIELDS IS UNCLEAR)
            limit (int, optional): maximum result items
            page (int, optional): page for chunked result lists
        Returns:
            dict: Business Object information (for all results)
                  or None if the request fails.

            Example response (for a Salesforce Account):
            {
                'links': {'data': {...}},
                'paging': {'limit': 500, 'page': 1, 'page_total': 1, 'range_max': 15, 'range_min': 1, 'total_count': 15},
                'results': {
                    'column_descriptions': [
                        {
                            'fieldLabel': 'AccountDetail.AccountID',
                            'fieldName': 'Account.ID',
                            'keyField': 'X',
                            'length': 18,
                            'position': 4
                        },
                        {
                            'fieldLabel': 'AccountName',
                            'fieldName': 'Account.Name',
                            'keyField': ' ',
                            'length': 255,
                            'position': 2
                        },
                        {
                            'fieldLabel': 'AccountNumber',
                            'fieldName': 'Account.AccountNumber',
                            'keyField': ' ',
                            'length': 40,
                            'position': 3
                        },
                        ...
                    ]
                    'max_rows_exceeded': False,
                    'result_rows': [
                        {
                            'AccountDetail.AccountID': '001Dn00000w0bCQIAY',
                            'AccountDetail.AccountName': 'Jet Stream Inc.',
                            'AccountDetail.AccountNumber': '1234567',
                            'AccountDetail.AccountOwner': 'Nick Wheeler',
                            'AccountDetail.AnnualRevenue': '$900001',
                            'AccountDetail.Description': '',
                            'AccountDetail.Employees': '',
                            'AccountDetail.Industry': 'Biotechnology',
                            'AccountDetail.ParentAccount': '',
                            ...
                        },
                        ...
                    ]
                }
            }
        """

        query = {
            "ext_system_id": external_system_id,
            "bo_type": type_name,
        }
        if limit:
            query["limit"] = limit
        if page:
            query["page"] = page
        if where_clauses:
            query.update(
                {("where_" + key): value for key, value in where_clauses.items()}
            )

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = self.config()["businessObjectsUrl"] + "?{}".format(encoded_query)
        request_header = self.request_form_header()

        logger.debug(
            "Get all business objects of type -> '%s' from external system -> %s; calling -> %s",
            type_name,
            external_system_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get business objects of type -> '{}' from external system -> {}".format(
                type_name, external_system_id
            ),
        )

    # end method definition

    def get_business_objects_search(
        self,
        external_system_id: str,
        type_name: str,
    ) -> dict | None:
        """Get business object type information. Unfortunately this REST API is
           pretty much limited. It does not return Field names of external system properties
           and also does not return property groups defined.

        Args:
            external_system_id (str): External system Id (such as "TM6")
            type_name (str): Type name of the business object (such as "SAP Customer")
        Returns:
            dict: Business Object Search Form or None if the request fails.
        """

        query = {
            "ext_system_id": external_system_id,
            "bo_type": type_name,
        }

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = self.config()["businessObjectsSearchUrl"] + "?{}".format(
            encoded_query
        )
        request_header = self.request_form_header()

        logger.debug(
            "Get search form for business object type -> '%s' and external system -> %s; calling -> %s",
            type_name,
            external_system_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get search form for business object type -> '{}' and external system -> {}".format(
                type_name, external_system_id
            ),
        )

    # end method definition

    def get_workspace_types(
        self, expand_workspace_info: bool = True, expand_templates: bool = True
    ) -> dict | None:
        """Get all workspace types configured in Extended ECM.

        Args:
            expand_workspace_info (bool, optional): Controls if the workspace info
                                                    is returned as well
            expand_templates (bool, optional): Controls if the list of workspace templates
                                               per workspace typ is returned as well
        Returns:
            dict: Workspace Types or None if the request fails.

            Example response:
            {
                'links': {
                    'data': {...}
                },
                'results': [
                    {
                        'data': {
                            'properties': {
                                'rm_enabled': False,
                                'templates': [
                                    {
                                        'id': 14471,
                                        'name': 'Campaign',
                                        'subtype': 848
                                    },
                                    ...
                                ],
                                'wksp_type_id': 35,
                                'wksp_type_name': 'Campaign'
                            },
                            'wksp_info': {
                                'wksp_type_icon': '/appimg/ot_bws/icons/13147%2Esvg?v=161108_84584'
                            }
                        }
                    }
                ]
            }
        """

        request_url = self.config()["businessWorkspaceTypesUrl"]
        if expand_templates:
            request_url += "?expand_templates=true"
        else:
            request_url += "?expand_templates=false"
        if expand_workspace_info:
            request_url += "&expand_wksp_info=true"
        else:
            request_url += "&expand_wksp_info=false"

        request_header = self.request_form_header()

        logger.debug("Get workspace types; calling -> %s", request_url)

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get workspace types",
        )

    # end method definition

    def get_workspace_create_form(
        self,
        template_id: int,
        external_system_id: str = None,
        bo_type: str = None,
        bo_id: str = None,
        parent_id: int = None,
    ) -> dict | None:
        """Get the Workspace create form.

        Args:
            template_id (int): ID of the workspace template
            external_system_id (str, optional): Identifier of the external system (None if no external system)
            bo_type (str, optional): Business object type (None if no external system)
            bo_id (str, optional): Business object identifier / key (None if no external system)
            parent_id (int, optional): Parent ID of the workspaces. Needs only be specified in special
                                       cases where workspace location cannot be derived from workspace
                                       type definition, e.g. sub-workspace
        Returns:
            dict: Workspace Create Form data or None if the request fails.
        """

        request_url = self.config()[
            "businessworkspacecreateform"
        ] + "?template_id={}".format(template_id)
        # Is a parent ID specifified? Then we need to add it to the request URL
        if parent_id is not None:
            request_url += "&parent_id={}".format(parent_id)
        # Is this workspace connected to a business application / external system?
        if external_system_id and bo_type and bo_id:
            request_url += "&ext_system_id={}".format(external_system_id)
            request_url += "&bo_type={}".format(bo_type)
            request_url += "&bo_id={}".format(bo_id)
            logger.debug(
                "Include business object connection -> (%s, %s, %s) in workspace create form...",
                external_system_id,
                bo_type,
                bo_id,
            )
        request_header = self.request_form_header()

        logger.debug(
            "Get workspace create form for workspace template ID -> %s; calling -> %s",
            str(template_id),
            request_url,
        )

        if parent_id:
            failure_message = "Failed to get workspace create form for template -> {} and parent ID -> {}".format(
                template_id, parent_id
            )
        else:
            failure_message = "Failed to get workspace create form for template -> {} (no parent ID given)".format(
                template_id
            )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message=failure_message,
        )

    # end method definition

    def get_workspace(self, node_id: int) -> dict | None:
        """Get a workspace based on the node ID.

        Args:
            node_id (int): Node ID of the workspace to retrieve.
        Returns:
            dict: Workspace node information or None if no node with this ID is found.

            Example response:
            {
                'links': {
                    'data': {...}
                },
                'meta_data': {
                    'properties': {...}
                },
                'paging': {
                    'limit': 500,
                    'page': 1,
                    'page_total': 1,
                    'range_max': 1,
                    'range_min': 1,
                    'total_count': 1
                },
                'results': [
                    {
                        'actions': {...},
                        'data': {
                            'business_properties': {
                                'business_object_id': '000004000240',
                                'business_object_type': 'BUS2007',
                                'business_object_type_id': 18,
                                'business_object_type_name': 'Maintenance Order',
                                'business_object_type_name_multilingual': {...},
                                'display_url': "https://fiori.qa.idea-te.eimdemo.com:8443/sap/bc/ui2/flp#MaintenanceOrder-displayXecmFactSheet&//C_ObjPgMaintOrder('000004000240')",
                                'external_system_id': 'TM6',
                                'external_system_name': 'TM6',
                                'has_default_display': True,
                                'has_default_search': True,
                                'isEarly': False,
                                'workspace_type_id': 42,
                                'workspace_type_name': 'Maintenance Order',
                                'workspace_type_name_multilingual': {},
                                ...
                            }
                            'properties': {
                                'volume_id': -2000,
                                'id': 36780,
                                'parent_id': 13567,
                                'owner_user_id': 7240,
                                'name': '4600000044 - C.E.B. New York Inc.',
                                'type': 848,
                                'description': '',
                                'create_date': '2023-09-02T11:07:06',
                                'create_user_id': 7240,
                                'create_user_id': 7240,
                                'modify_date': '2023-09-02T11:07:11',
                                'modify_user_id': 7240,
                                'reserved': False,
                                'reserved_user_id': 0,
                                'reserved_date': None,
                                'order': None,
                                'icon': '/cssupport/otsapxecm/wksp_contract_vendor.png',
                                'hidden': False,
                                'mime_type': None,
                                'original_id': 0,
                                'wnf_wksp_type_id': 16,
                                'wnf_wksp_template_id': 15615,
                                'size_formatted': '7 Items',
                                'type_name': 'Business Workspace',
                                'container': True,
                                'size': 7,
                                ...
                            }
                            'wksp_info':
                            {
                                'wksp_type_icon': '/appimg/ot_bws/icons/16634%2Esvg?v=161194_13949'
                            }
                        },
                        'metadata': {...},
                        'metadata_order': {
                            'categories': ['16878']
                        }
                    }
                ],
                'wksp_info': {
                    'wksp_type_icon': None
                }
                'workspace_references': [
                    {
                        'business_object_id': '000004000240',
                        'business_object_type': 'BUS2007',
                        'business_object_type_id': 18,
                        'external_system_id': 'TM6',
                        'has_default_display': True,
                        'has_default_search': True,
                        'workspace_type_id': 42
                    }
                ]
            }
        """

        request_url = self.config()["businessWorkspacesUrl"] + "/" + str(node_id)
        request_header = self.request_form_header()

        logger.debug(
            "Get workspace with ID -> %s; calling -> %s", str(node_id), request_url
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get workspace with ID -> {}".format(node_id),
        )

    # end method definition

    def get_workspace_instances(
        self, type_name: str = "", type_id: int = None, expanded_view: bool = True
    ):
        """Get all workspace instances of a given type. This is a convenience
           wrapper method for get_workspace_by_type_and_name()

        Args:
            type_name (str, optional): Name of the workspace type
            type_id (int, optional): ID of the workspace_type
            expanded_view (bool, optional): If 'False' then just search in recently
                                            accessed business workspace for this name and type.
                                            If 'True' (this is the default) then search in all
                                            workspaces for this name and type.
        Returns:
            dict: Workspace information or None if the workspace is not found.
        """

        # Omitting the name lets it return all instances of the type:
        return self.get_workspace_by_type_and_name(
            type_name=type_name, type_id=type_id, name="", expanded_view=expanded_view
        )

    # end method definition

    def get_workspace_by_type_and_name(
        self,
        type_name: str = "",
        type_id: int = None,
        name: str = "",
        expanded_view: bool = True,
        page: int | None = None,
        limit: int | None = None,
        timeout: int = REQUEST_TIMEOUT,
    ) -> dict | None:
        """Lookup workspace based on workspace type and workspace name.

        Args:
            type_name (str, optional): name of the workspace type
            type_id (int, optional): ID of the workspace_type
            name (str, optional): Name of the workspace, if "" then deliver all instances
                                  of the given workspace type.
            expanded_view (bool, optional): If 'False' then just search in recently
                                            accessed business workspace for this name and type.
                                            If 'True' (this is the default) then search in all
                                            workspaces for this name and type.
            timeout (int, optional): timeout for the request in seconds
        Returns:
            dict: Workspace information or None if the workspace is not found.
        """

        if not type_name and not type_id:
            logger.error(
                "No workspace type specified - neither by type name nor type ID. Cannot lookup workspace(s)!"
            )
            return None

        # Add query parameters (these are NOT passed via JSon body!)
        query = {
            "expanded_view": expanded_view,
        }
        if type_name:
            query["where_workspace_type_name"] = type_name
        if type_id:
            query["where_workspace_type_id"] = type_id
        if name:
            query["where_name"] = name
        if page and limit:
            query["page"] = page
            query["limit"] = limit

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = self.config()["businessWorkspacesUrl"] + "?{}".format(
            encoded_query
        )
        request_header = self.request_form_header()

        if name:
            logger.debug(
                "Get workspace with name -> '%s' and type -> '%s'; calling -> %s",
                name,
                type_name,
                request_url,
            )
            failure_message = (
                "Failed to get workspace with name -> '{}' and type -> '{}'".format(
                    name, type_name
                )
            )
        else:
            if type_name:
                logger.debug(
                    "Get all workspace instances of type -> '%s'; calling -> %s",
                    type_name,
                    request_url,
                )
                failure_message = (
                    "Failed to get all workspace instances of type -> '{}'".format(
                        type_name
                    )
                )
            else:
                logger.debug(
                    "Get all workspace instances with type ID -> %s; calling -> %s",
                    str(type_id),
                    request_url,
                )
                failure_message = (
                    "Failed to get all workspace instances with type ID -> {}".format(
                        type_id
                    )
                )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=timeout,
            failure_message=failure_message,
        )

    # end method definition

    def get_workspace_type_location(
        self,
        type_name: str = "",
        type_id: int = None,
    ) -> int | None:
        """Determine the folder in which the workspace instances of a given type reside.
           Either the type ID or the type name need to be provided. NOTE: workspace types
           may not always have a default location for all its instances. In such case
           parent_id may just be the folder of the first delivered workspace instance.

        Args:
            type_name (str, optional): Name of the workspace type. Defaults to "".
            type_id (int, optional): ID of the workspace type. Defaults to None.

        Returns:
            int | None: node ID of the parent folder
        """

        # it seems there's no other way to get the workspace location configured for a
        # workspace type other then getting an example workspace of this type and see what
        # the parent is. The REST API used for get_workspace_types() does not deliver this information :-(
        response = self.get_workspace_by_type_and_name(
            type_name=type_name, type_id=type_id, page=1, limit=1
        )
        parent_id = self.get_result_value(response=response, key="parent_id")

        return parent_id

    # end method definition

    def get_workspace_by_business_object(
        self,
        external_system_name: str,
        business_object_type: str,
        business_object_id: str,
        return_workspace_metadata: bool = False,
        show_error: bool = False,
    ) -> dict | None:
        """Get a workspace based on the business object of an external system.

        Args:
            external_system_name (str): Name of the connection
            business_object_type (str): Type of the Business object, e.g. KNA1 for SAP customers
            business_object_id (str): ID of the business object in the external system
            return_workspace_metadata (bool, optional): Whether or not workspace metadata (categories) should be returned.
                                                        Default is False.
            show_error (bool, optional): Treat as error if node is not found. Default is False.
        Returns:
            dict: Workspace node information or None if no node with this ID is found.

            Example response:
            {
                'links': {
                    'data': {...}
                },
                'meta_data': {
                    'properties': {...}
                },
                'paging': {
                    'limit': 500,
                    'page': 1,
                    'page_total': 1,
                    'range_max': 1,
                    'range_min': 1,
                    'total_count': 1
                },
                'results': [
                    {
                        'actions': {...},
                        'data': {
                            'properties': {
                                'volume_id': -2000,
                                'id': 36780,
                                'parent_id': 13567,
                                'owner_user_id': 7240,
                                'name': '4600000044 - C.E.B. New York Inc.',
                                'type': 848,
                                'description': '',
                                'create_date': '2023-09-02T11:07:06',
                                'create_user_id': 7240,
                                'create_user_id': 7240,
                                'modify_date': '2023-09-02T11:07:11',
                                'modify_user_id': 7240,
                                'reserved': False,
                                'reserved_user_id': 0,
                                'reserved_date': None,
                                'order': None,
                                'icon': '/cssupport/otsapxecm/wksp_contract_vendor.png',
                                'hidden': False,
                                'mime_type': None,
                                'original_id': 0,
                                'wnf_wksp_type_id': 16,
                                'wnf_wksp_template_id': 15615,
                                'size_formatted': '7 Items',
                                'type_name': 'Business Workspace',
                                'container': True,
                                'size': 7,
                                ...
                            }
                        },
                        'metadata': {...},
                        'metadata_order': {...}
                    }
                ],
                'wksp_info': {
                    'wksp_type_icon': None
                }
            }
        """

        request_url = (
            self.config()["externalSystemUrl"]
            + "/"
            + external_system_name
            + "/botypes/"
            + business_object_type
            + "/boids/"
            + business_object_id
        )
        if return_workspace_metadata:
            request_url += "?metadata"

        request_header = self.request_form_header()

        logger.debug(
            "Get workspace via external system -> '%s' (Business Object Type -> '%s'; Business Object ID -> %s); calling -> %s",
            external_system_name,
            business_object_type,
            business_object_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            warning_message="Cannot get workspace via external system -> '{}', Business Object Type -> '{}', and Business Object ID -> {}. It does not exist.".format(
                external_system_name, business_object_type, business_object_id
            ),
            failure_message="Failed to get workspace via external system -> '{}', Business Object Type -> '{}', and Business Object ID -> {}".format(
                external_system_name, business_object_type, business_object_id
            ),
            show_error=show_error,
        )

    # end method definition

    def set_workspace_reference(
        self,
        workspace_id: int,
        external_system_id: str | None = None,
        bo_type: str | None = None,
        bo_id: str | None = None,
        show_error: bool = True,
    ):
        """Set reference of workspace to a business object in an external system

        Args:
            workspace_id (int): ID of the workspace
            external_system_id (str, optional): Identifier of the external system (None if no external system)
            bo_type (str, optional): Business object type (None if no external system)
            bo_id (str, optional): Business object identifier / key (None if no external system)
            show_error (bool, optional): Log an error if workspace cration fails. Otherwise log a warning.
        """

        request_url = (
            self.config()["businessWorkspacesUrl"]
            + "/"
            + str(workspace_id)
            + "/workspacereferences"
        )
        request_header = self.request_form_header()

        if not external_system_id or not bo_type or not bo_id:
            logger.error(
                "Cannot update workspace reference - required Business Object information is missing!"
            )
            return None

        logger.debug(
            "Update workspace reference of workspace ID -> %s with business object connection -> (%s, %s, %s); calling -> %s",
            str(workspace_id),
            external_system_id,
            bo_type,
            bo_id,
            request_url,
        )

        workspace_put_data = {
            "ext_system_id": external_system_id,
            "bo_type": bo_type,
            "bo_id": bo_id,
        }

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data=workspace_put_data,
            timeout=None,
            warning_message="Cannot update reference for workspace ID -> {} with business object connection -> ({}, {}, {})".format(
                workspace_id, external_system_id, bo_type, bo_id
            ),
            failure_message="Failed to update reference for workspace ID -> {} with business object connection -> ({}, {}, {})".format(
                workspace_id, external_system_id, bo_type, bo_id
            ),
            show_error=show_error,
        )

    # end method definition

    def create_workspace(
        self,
        workspace_template_id: int,
        workspace_name: str,
        workspace_description: str,
        workspace_type: int,
        category_data: dict | None = None,
        external_system_id: str | None = None,
        bo_type: str | None = None,
        bo_id: str | None = None,
        parent_id: int | None = None,
        ibo_workspace_id: int | None = None,
        external_modify_date: str | None = None,
        external_create_date: str | None = None,
        show_error: bool = True,
    ) -> dict | None:
        """Create a new business workspace.

        Args:
            workspace_template_id (int): ID of the workspace template
            workspace_name (str): Name of the workspace
            workspace_description (str): Description of the workspace
            workspace_type (int): Type ID of the workspace
            category_data (dict): Category and attributes
            external_system_id (str, optional): Identifier of the external system (None if no external system)
            bo_type (str, optional): Business object type (None if no external system)
            bo_id (str, optional): Business object identifier / key (None if no external system)
            parent_id (str, optional): Parent ID of the workspaces. Needs only be specified in special
                                       cases where workspace location cannot be derived from workspace
                                       type definition or if it is a sub-workspace.
            ibo_workspace_id (int, optional): Node ID of an existing workspace that is already connected to another
                                              external system. This allows for subsequent calls to coonect the workspace
                                              to multiple Business Objects (IBO = Identical Business Objects)
            external_create_date (str, optional) value of the source system in format 2024-06-24
            external_modify_date (str, optional) value of the source system in format 2024-06-24
            show_error (bool, optional): Log an error if workspace cration fails. Otherwise log a warning.
        Returns:
            dict: Workspace Create Form data or None if the request fails.
        """

        # Avoid linter warning W0102
        if category_data is None:
            category_data = {}

        create_workspace_post_data = {
            "template_id": str(workspace_template_id),
            "name": workspace_name,
            "description": workspace_description,
            "wksp_type_id": str(workspace_type),
            "type": str(848),
            "roles": category_data,
            "external_create_date": external_create_date,
            "external_modify_date": external_modify_date,
        }

        # Is this workspace connected to a business application / external system?
        if external_system_id and bo_type and bo_id:
            create_workspace_post_data["ext_system_id"] = external_system_id
            create_workspace_post_data["bo_type"] = bo_type
            create_workspace_post_data["bo_id"] = bo_id
            logger.debug(
                "Use business object connection -> (%s, %s, %s) for workspace -> '%s'",
                external_system_id,
                bo_type,
                bo_id,
                workspace_name,
            )
            if ibo_workspace_id:
                logger.debug(
                    "This is a subsequent call to create a cross-application workspace (IBO)"
                )
                create_workspace_post_data["ibo_workspace_id"] = ibo_workspace_id

        # If workspace creation location cannot be derived from the workspace type
        # there may be an optional parent parameter passed to this method. This can
        # also be the case if workspaces are nested into each other:
        if parent_id is not None:
            create_workspace_post_data["parent_id"] = parent_id
            logger.debug(
                "Use specified location -> %s for workspace -> '%s'",
                str(parent_id),
                workspace_name,
            )
        else:
            logger.debug(
                "Determine location of workspace -> '%s' via workspace type -> '%s'",
                workspace_name,
                str(workspace_type),
            )

        request_url = self.config()["businessWorkspacesUrl"]
        request_header = self.request_form_header()

        logger.debug(
            "Create workspace -> '%s' with type -> '%s' from template -> %s; calling -> %s",
            workspace_name,
            str(workspace_type),
            str(workspace_template_id),
            request_url,
        )

        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        # See https://developer.opentext.com/apis/14ba85a7-4693-48d3-8c93-9214c663edd2/4403207c-40f1-476a-b794-fdb563e37e1f/07229613-7ef4-4519-8b8a-47eaff639d42#operation/createBusinessWorkspace
        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data={"body": json.dumps(create_workspace_post_data)},
            timeout=None,
            warning_message="Failed to create workspace -> '{}' from template with ID -> {}".format(
                workspace_name, workspace_template_id
            ),
            failure_message="Failed to create workspace -> '{}' from template with ID -> {}".format(
                workspace_name, workspace_template_id
            ),
            show_error=show_error,
        )

    # end method definition

    def update_workspace(
        self,
        workspace_id: int,
        workspace_name: str | None = None,
        workspace_description: str | None = None,
        category_data: dict | None = None,
        external_system_id: str | None = None,
        bo_type: str | None = None,
        bo_id: str | None = None,
        external_modify_date: str | None = None,
        external_create_date: str | None = None,
        show_error: bool = True,
    ) -> bool:
        """Update an existing business workspace. This is a wrapper method to update
           a combination of workspace name / description, workspace reference, and workspace metadata

        Args:
            workspace_id (int): ID of the workspace
            workspace_name (str): New Name of the workspace
            workspace_description (str): New Description of the workspace
            category_data (dict): Category and attributes
            external_system_id (str, optional): Identifier of the external system (None if no external system)
            bo_type (str, optional): Business object type (None if no external system)
            bo_id (str, optional): Business object identifier / key (None if no external system)
            show_error (bool, optional): Log an error if workspace cration fails. Otherwise log a warning.
        Returns:
            dict: Response of the REST API call or None if the request fails.
        """

        # Should we connect this workspace to a business application / external system?
        if external_system_id and bo_type and bo_id:
            response = self.set_workspace_reference(
                workspace_id=workspace_id,
                external_system_id=external_system_id,
                bo_type=bo_type,
                bo_id=bo_id,
                show_error=show_error,
            )
            if not response:
                return False

        # Should we change the name and/or the description or the category data of this workspace?
        if workspace_name or workspace_description:
            response = self.update_item(
                node_id=workspace_id,
                item_name=workspace_name,
                item_description=workspace_description,
                category_data=category_data,
                external_create_date=external_create_date,
                external_modify_date=external_modify_date,
            )
            if not response:
                return False

        return True

    # end method definition

    def create_workspace_relationship(
        self,
        workspace_id: int,
        related_workspace_id: int,
        relationship_type: str = "child",
        show_error: bool = True,
    ) -> dict | None:
        """Create a relationship between two workspaces.

        Args:
            workspace_id (int): ID of the workspace
            related_workspace_id (int): ID of the related workspace
            relationship_type (str, optional): "parent" or "child" - "child" is default if omitted
            show_error (bool, optional): Log an error if relationship cration fails.
                                         Otherwise log a warning.
        Returns:
            dict: Workspace Relationship data (json) or None if the request fails.
        """

        create_workspace_relationship_post_data = {
            "rel_bw_id": str(related_workspace_id),
            "rel_type": relationship_type,
        }

        request_url = self.config()[
            "businessWorkspacesUrl"
        ] + "/{}/relateditems".format(workspace_id)
        request_header = self.request_form_header()

        logger.debug(
            "Create workspace relationship between -> %s and -> %s; calling -> %s",
            str(workspace_id),
            str(related_workspace_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=create_workspace_relationship_post_data,
            timeout=None,
            warning_message="Cannot create workspace relationship between -> {} and -> {}. It may already exist.".format(
                workspace_id, related_workspace_id
            ),
            failure_message="Failed to create workspace relationship between -> {} and -> {}".format(
                workspace_id, related_workspace_id
            ),
            show_error=show_error,
        )

    # end method definition

    def get_workspace_relationships(
        self,
        workspace_id: int,
        relationship_type: str | None = None,
        related_workspace_name: str | None = None,
        related_workspace_type_id: int | None = None,
    ) -> dict | None:
        """Get the Workspace relationships to other workspaces. Optionally, filter criterias can be provided
           such as the related workspace name (starts with) or the related workspace TYPE ids (one or multiple)

        Args:
            workspace_id (int): ID of the workspace template
            relationship_type (str): Either "parent" or "child" (or None = unspecified which is the default)
            related_workspace_name (str, optional): filter for a certain workspace name in the related items.
            related_workspace_type_id (int | None): ID of related workspace type (or list of IDs)
        Returns:
            dict: Workspace relationships or None if the request fails.
        """

        request_url = (
            self.config()["businessWorkspacesUrl"]
            + "/"
            + str(workspace_id)
            + "/relateditems"
        )

        query = {}

        if relationship_type:
            query["where_relationtype"] = relationship_type

        if related_workspace_name:
            query["where_name"] = related_workspace_name

        if related_workspace_type_id:
            query["where_workspace_type_id"] = related_workspace_type_id

        encoded_query = urllib.parse.urlencode(query, doseq=False)
        request_url += "?{}".format(encoded_query)

        request_header = self.request_form_header()

        logger.debug(
            "Get related workspaces for workspace with ID -> %s; calling -> %s",
            str(workspace_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get related workspaces of workspace with ID -> {}".format(
                workspace_id
            ),
        )

    # end method definition

    def get_workspace_roles(self, workspace_id: int) -> dict | None:
        """Get the Workspace roles.

        Args:
            workspace_id (int): ID of the workspace template or workspace
        Returns:
            dict: Workspace Roles data or None if the request fails.
        """

        request_url = (
            self.config()["businessWorkspacesUrl"] + "/" + str(workspace_id) + "/roles"
        )
        request_header = self.request_form_header()

        logger.debug(
            "Get workspace roles of workspace with ID -> %s; calling -> %s",
            str(workspace_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get roles of workspace with ID -> {}".format(
                workspace_id
            ),
        )

    # end method definition

    def get_workspace_members(self, workspace_id: int, role_id: int) -> dict | None:
        """Get the Workspace members of a given role.

        Args:
            workspace_id (int): ID of the workspace template
            role_id (int): ID of the role
        Returns:
            dict: Workspace member data or None if the request fails.
        """

        request_url = self.config()[
            "businessWorkspacesUrl"
        ] + "/{}/roles/{}/members".format(workspace_id, role_id)
        request_header = self.request_form_header()

        logger.debug(
            "Get workspace members for workspace ID -> %s and role ID -> %s; calling -> %s",
            str(workspace_id),
            str(role_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get workspace members",
        )

    # end method definition

    def add_workspace_member(
        self, workspace_id: int, role_id: int, member_id: int, show_warning: bool = True
    ) -> dict | None:
        """Add member to a workspace role. Check that the user/group is not yet a member.

        Args:
            workspace_id (int): ID of the workspace
            role_id (int): ID of the role
            member_id (int): User ID or Group ID
            show_warning (bool, optional): If True logs a warning if member is already in role
        Returns:
            dict: Workspace Role Membership or None if the request fails.
        """

        logger.debug(
            "Check if user/group with ID -> %s is already in role with ID -> %s of workspace with ID -> %s",
            str(member_id),
            str(role_id),
            str(workspace_id),
        )

        workspace_members = self.get_workspace_members(
            workspace_id=workspace_id, role_id=role_id
        )

        if self.exist_result_item(workspace_members, "id", member_id):
            if show_warning:
                logger.warning(
                    "User/group with ID -> %s is already a member of role with ID -> %s of workspace with ID -> %s",
                    str(member_id),
                    str(role_id),
                    str(workspace_id),
                )
            return workspace_members

        add_workspace_member_post_data = {"id": str(member_id)}

        request_url = self.config()[
            "businessWorkspacesUrl"
        ] + "/{}/roles/{}/members".format(workspace_id, role_id)
        request_header = self.request_form_header()

        logger.debug(
            "Add user/group with ID -> %s to role with ID -> %s of workspace with ID -> %s; calling -> %s",
            str(member_id),
            str(role_id),
            str(workspace_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=add_workspace_member_post_data,
            timeout=None,
            failure_message="Failed to add user/group with ID -> {} to role with ID -> {} of workspace with ID -> {}".format(
                member_id, role_id, workspace_id
            ),
        )

    # end method definition

    def remove_workspace_member(
        self, workspace_id: int, role_id: int, member_id: int, show_warning: bool = True
    ) -> dict | None:
        """Remove a member from a workspace role. Check that the user is currently a member.

        Args:
            workspace_id (int): ID of the workspace
            role_id (int): ID of the role
            member_id (int): User or Group Id
            show_warning (bool, optional): If True logs a warning if member is not in role
        Returns:
            dict: Workspace Role Membership or None if the request fails.
        """

        logger.debug(
            "Check if user/group with ID -> %s is in role with ID -> %s of workspace with ID -> %s",
            str(member_id),
            str(role_id),
            str(workspace_id),
        )

        workspace_members = self.get_workspace_members(
            workspace_id=workspace_id, role_id=role_id
        )

        if not self.exist_result_item(workspace_members, "id", member_id):
            if show_warning:
                logger.warning(
                    "User/group with ID -> %s is not a member of role with ID -> %s of workspace with ID -> %s",
                    str(member_id),
                    str(role_id),
                    str(workspace_id),
                )
            return None

        request_url = self.config()[
            "businessWorkspacesUrl"
        ] + "/{}/roles/{}/members/{}".format(workspace_id, role_id, member_id)
        request_header = self.request_form_header()

        logger.debug(
            "Removing user/group with ID -> %s from role with ID -> %s of workspace with ID -> %s; calling -> %s",
            str(member_id),
            str(role_id),
            str(workspace_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="DELETE",
            headers=request_header,
            timeout=None,
            failure_message="Failed to remove user/group with ID -> {} from role with ID -> {} of workspace with ID -> {}".format(
                member_id, role_id, workspace_id
            ),
        )

    # end method definition

    def remove_workspace_members(
        self, workspace_id: int, role_id: int, show_warning: bool = True
    ) -> bool:
        """Remove all members from a workspace role. Check that the user is currently a member.

        Args:
            workspace_id (int): ID of the workspace
            role_id (int): ID of the role
            show_warning (bool, optional): If True logs a warning if member is not in role
        Returns:
            dict: Workspace Role Membership or None if the request fails.
        """

        workspace_members = self.get_workspace_members(
            workspace_id=workspace_id, role_id=role_id
        )

        # Get the list of existing workspace_member ids:
        workspace_member_ids = self.get_result_values(workspace_members, "id")
        if not workspace_member_ids:
            return False

        for workspace_member_id in workspace_member_ids:
            self.remove_workspace_member(
                workspace_id=workspace_id,
                role_id=role_id,
                member_id=workspace_member_id,
                show_warning=show_warning,
            )

        return True

    # end method definition

    def assign_workspace_permissions(
        self, workspace_id: int, role_id: int, permissions: list, apply_to: int = 2
    ) -> dict | None:
        """Update permissions of a workspace role
        Args:
            workspace_id (int): ID of the workspace
            role_id (int): ID of the role
            permissions (list): List of permissions - potential elements:
                                "see"
                                "see_contents"
                                "modify"
                                "edit_attributes"
                                "add_items"
                                "reserve"
                                "add_major_version"
                                "delete_versions"
                                "delete"
                                "edit_permissions"
            apply_to (int, optional):  Items to apply the permission change. Possible values:
                                       0 = this item
                                       1 = sub-items
                                       2 = This item and sub-items (default)
                                       3 = This item and immediate sub-items
        Returns:
            dict: Workspace Role Membership or None if the request fails.
        """

        request_url = self.config()["businessWorkspacesUrl"] + "/{}/roles/{}".format(
            workspace_id, role_id
        )

        request_header = self.request_form_header()

        logger.debug(
            "Updating Permissions of role with ID -> %s of workspace with ID -> %s with permissions -> %s; calling -> %s",
            str(role_id),
            str(workspace_id),
            str(permissions),
            request_url,
        )

        permission_put_data = {
            "permissions": permissions,
            "apply_to": apply_to,
        }

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data={"body": json.dumps(permission_put_data)},
            timeout=None,
            failure_message="Failed to update permissions for role with ID -> {} of workspace with ID -> {}".format(
                role_id, workspace_id
            ),
        )

    # end method definition

    def update_workspace_icon(
        self, workspace_id: int, file_path: str, file_mimetype: str = "image/*"
    ) -> dict | None:
        """Update a workspace with a with a new icon (which is uploaded).

        Args:
            workspace_id (int): ID of the workspace
            file_path (str): path + filename of icon file
            file_mimetype (str, optional): mimetype of the image
        Returns:
            dict: Node information or None if REST call fails.
        """

        if not os.path.exists(file_path):
            logger.error("Workspace icon file does not exist -> %s", file_path)
            return None

        update_workspace_icon_post_body = {
            "file_content_type": file_mimetype,
            "file_filename": os.path.basename(file_path),
        }

        upload_workspace_icon_post_files = [
            (
                "file",
                (
                    f"{os.path.basename(file_path)}",
                    open(file_path, "rb"),
                    file_mimetype,
                ),
            )
        ]

        request_url = (
            self.config()["businessWorkspacesUrl"] + "/" + str(workspace_id) + "/icons"
        )

        request_header = self.cookie()

        logger.debug(
            "Update icon for workspace ID -> %s with icon file -> %s; calling -> %s",
            str(workspace_id),
            file_path,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=update_workspace_icon_post_body,
            files=upload_workspace_icon_post_files,
            timeout=None,
            failure_message="Failed to update workspace ID -> {} with new icon -> '{}'".format(
                workspace_id, file_path
            ),
        )

    # end method definition

    def get_unique_names(self, names: list, subtype: int | None = None) -> dict | None:
        """Get definition information for Unique Names.

        Args:
            names (list): list of unique names to lookup.
            subtype (int): filter unique names for those pointing to a specific subtype

        Returns:
            dict | None: Unique name definition information or None if REST call fails.

            Example response:
            {
                'links': {'data': {...}},
                'results': [
                    {
                        'NodeId': 13653,
                        'NodeName': 'Functional Location',
                        'UniqueName': 'ot_templ_func_location'
                    },
                    {
                        'NodeId': 2424,
                        'NodeName': 'Content Server Document Templates',
                        'UniqueName': 'Document Templates'
                    }
                ]
            }
        """

        if not names:
            logger.error("Missing Unique Names!")
            return None

        # Add query parameters (these are NOT passed via JSon body!)
        query = {"where_names": "{" + ", ".join(names) + "}"}
        if subtype:
            query["where_subtype"] = subtype

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = self.config()["uniqueNamesUrl"] + "?{}".format(encoded_query)
        request_header = self.request_form_header()

        if subtype:
            logger.debug(
                "Get unique names -> %s of subtype -> %s; calling -> %s",
                str(names),
                str(subtype),
                request_url,
            )
            warning_message = (
                "Failed to get unique names -> {} of subtype -> {}".format(
                    names, subtype
                )
            )
        else:
            logger.debug(
                "Get unique names -> %s; calling -> %s",
                str(names),
                request_url,
            )
            warning_message = "Failed to get unique names -> {}".format(names)

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            warning_message=warning_message,
            show_error=False,
        )

    # end method definition

    def create_item(
        self,
        parent_id: int,
        item_type: str,
        item_name: str,
        item_description: str = "",
        url: str = "",
        original_id: int = 0,
        show_error: bool = True,
    ) -> dict | None:
        """Create an Extended ECM item. This REST call is somewhat limited. It cannot set featured item or hidden item.
           It does also not accept owner group information.

        Args:
            parent_id (int): Node ID of the parent
            item_type (str): Type of the item (e.g. 0 = folder, 140 = URL)
            item_name (str): Name of the item
            item_description (str, optional): Description of the item
            url (str, optional): Address of the URL item (if it is an URL item type)
            original_id (int, optional): Node ID of the original (referenced) item.
                                         Required if a shortcut item is created
            show_error (bool, optional): Log an error if item cration fails. Otherwise log a warning.
        Returns:
            dict: Request response of the create item call or None if the REST call has failed.
        """

        create_item_post_data = {
            "parent_id": parent_id,
            "type": item_type,
            "name": item_name,
            "description": item_description,
        }

        if url:
            create_item_post_data["url"] = url
        if original_id > 0:
            create_item_post_data["original_id"] = original_id

        request_url = self.config()["nodesUrlv2"]
        request_header = self.request_form_header()

        logger.debug(
            "Create item -> '%s' (type -> %s) under parent with ID -> %s; calling -> %s",
            item_name,
            item_type,
            str(parent_id),
            request_url,
        )

        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data={"body": json.dumps(create_item_post_data)},
            timeout=None,
            warning_message="Cannot create item -> '{}'".format(item_name),
            failure_message="Failed to create item -> '{}'".format(item_name),
            show_error=show_error,
        )

    # end method definition

    def update_item(
        self,
        node_id: int,
        parent_id: int | None = None,
        item_name: str | None = None,
        item_description: str | None = None,
        category_data: dict | None = None,
        external_modify_date: str | None = None,
        external_create_date: str | None = None,
    ) -> dict | None:
        """Update an Extended ECM item (parent, name, description, metadata). Changing the parent ID is
           a move operation. If parent ID = 0 or None the item will not be moved.

        Args:
            node_id (int): ID of the node
            parent_id (int | None, optional): node ID of the new parent (in case of a move operation)
            item_name (str | None, optional): new name of the item
            item_description (str | None, optional): new description of the item
            category_data (dict | None): new category and attributes values
            external_create_date (str, optional) value of the source system in format 2024-06-24
            external_modify_date (str, optional) value of the source system in format 2024-06-24
        Returns:
            dict: Response of the update item request or None if the REST call has failed.
        """

        update_item_put_data = {}

        if item_name:
            # this is a rename operation
            update_item_put_data["name"] = item_name
        if item_description:
            # this is a change description operation
            update_item_put_data["description"] = item_description
        if parent_id:
            # this is a move operation
            update_item_put_data["parent_id"] = parent_id

        # Set external dates if provided:
        if external_create_date:
            update_item_put_data["external_create_date"] = external_create_date
        if external_modify_date:
            update_item_put_data["external_modify_date"] = external_modify_date

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id)
        request_header = self.request_form_header()

        logger.debug(
            "Update item -> '%s' (%s) with data -> %s; calling -> %s",
            item_name,
            node_id,
            str(update_item_put_data),
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data={"body": json.dumps(update_item_put_data)},
            timeout=None,
            failure_message="Failed to update item -> '{}' ({})".format(
                item_name, node_id
            ),
        )

        if response and category_data:
            for category in category_data:
                response = self.set_category_values(
                    node_id=node_id,
                    category_id=category,
                    category_data=category_data[category],
                )

        return response

    # end method definition

    def get_document_templates(self, parent_id: int):
        """Get all document templates for a given target location.

        Args:
            parent_id (int): node ID of target location (e.g. a folder)

        Returns:
            dict: response of the REST call (converted to a Python dictionary)

            Example response:
            'results': [
                {
                    'container': False,
                    'hasTemplates': False,
                    'name': 'Document',
                    'subtype': 144,
                    'templates': [
                        {
                            'description_multilingual': {...},
                            'id': 16817,
                            'isDPWizardAvailable': False,
                            'mime_type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                            'name': 'Innovate Procurement Contract Template 2022.docx',
                            'name_multilingual': {...},
                            'size': 144365,
                            'sizeformatted': '141 KB',
                            'type': 144
                        },
                        {
                            ...
                        }
                    ]
                }
            ]
        """

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(parent_id)
            + "/doctemplates?subtypes={144}&sidepanel_subtypes={144}"
        )
        request_header = self.request_form_header()

        logger.debug(
            "Get document templates for target location -> %s (parent ID); calling -> %s",
            str(parent_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get document templates for parent folder with ID -> {}".format(
                parent_id
            ),
        )

    # end method definition

    def create_document_from_template(
        self,
        template_id: int,
        parent_id: int,
        classification_id: int,
        category_data: dict | None,
        doc_name: str,
        doc_desciption: str = "",
    ) -> dict | None:
        """Create a document based on a document template

        Args:
            template_id (int): node ID of the document template
            parent_id (int): node ID of the target location (parent)
            classification_id (int): node ID of the classification
            category_data (dict): metadata / category data
                                    Example: category ID = 12508
                                    {
                                        "12508": {
                                            "12508_2": "Draft",         # Text drop-down
                                            "12508_3": 8559,            # user ID
                                            "12508_4": "2023-05-10",    # date
                                            "12508_6": 7357,            # user ID
                                            "12508_7": "2023-05-11",    # date
                                            "12508_5": True,            # checkbox / bool
                                            "12508_8": "EN",            # text drop-down
                                            "12508_9": "MS Word",       # text drop-down
                                        }
                                    }
            doc_name (str): Name of the item to create.
            doc_description (str, optional): Description of the item to create.
        """

        create_document_post_data = {
            "template_id": template_id,
            "parent_id": parent_id,
            "name": doc_name,
            "description": doc_desciption,
            "type": 144,
            "roles": {
                "categories": category_data,
                "classifications": {"create_id": [classification_id], "id": []},
            },
        }

        request_url = self.config()["doctemplatesUrl"]
        request_header = self.request_form_header()

        logger.debug(
            "Create document -> '%s' from template with ID -> %s in target location with ID -> %s with classification ID -> %s; calling -> %s",
            doc_name,
            str(template_id),
            str(parent_id),
            str(classification_id),
            request_url,
        )

        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            # this seems to only work with a "body" tag and is different form the documentation
            # on developer.opentext.com
            data={"body": json.dumps(create_document_post_data)},
            timeout=None,
            failure_message="Failed to create document -> '{}'".format(doc_name),
        )

    # end method definition

    def create_wiki(
        self,
        parent_id: int,
        name: str,
        description: str = "",
        show_error: bool = True,
    ) -> dict | None:
        """Create an Extended ECM Wiki.

        Args:
            parent_id (int): Node ID of the parent
            name (str): Name of the wiki item
            description (str, optional): Description of the wiki item
            show_error (bool, optional): Log an error if item cration fails. Otherwise log a warning.
        Returns:
            dict: Request response of the create item call or None if the REST call has failed.
        """

        create_wiki_post_data = {
            "parent_id": parent_id,
            "type": 5573,
            "name": name,
            "description": description,
        }

        request_url = self.config()["nodesUrlv2"]
        request_header = self.request_form_header()

        logger.debug(
            "Create wiki -> '%s' under parent with ID -> %s; calling -> %s",
            name,
            str(parent_id),
            request_url,
        )

        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data={"body": json.dumps(create_wiki_post_data)},
            timeout=None,
            warning_message="Cannot create wiki -> '{}'".format(name),
            failure_message="Failed to create wiki -> '{}'".format(name),
            show_error=show_error,
        )

    # end method definition

    def create_wiki_page(
        self,
        wiki_id: int,
        name: str,
        content: str = "",
        description: str = "",
        show_error: bool = True,
    ) -> dict | None:
        """Create an Extended ECM wiki page.

        Args:
            wiki_id (int): Node ID of the wiki
            name (str): Name of the wiki page
            content (str, optional): Content of the page (typically HTML)
            show_error (bool, optional): Log an error if item cration fails. Otherwise log a warning.
        Returns:
            dict: Request response of the create wiki page call or None if the REST call has failed.
        """

        create_wiki_page_post_data = {
            "parent_id": wiki_id,
            "type": 5574,
            "name": name,
            "description": description,
            "TextField": content,
        }

        request_url = self.config()["nodesUrl"]
        # Header needs to just include the cookie:
        request_header = self.cookie()

        logger.debug(
            "Create wiki page -> '%s' in wiki with ID -> %s; calling -> %s",
            name,
            str(wiki_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=create_wiki_page_post_data,
            timeout=None,
            warning_message="Cannot create wiki page -> '{}'".format(name),
            failure_message="Failed to create wiki page -> '{}'".format(name),
            show_error=show_error,
        )

    # end method definition

    def get_web_report_parameters(self, nickname: str) -> list | None:
        """Get parameters of a Web Report in Extended ECM. These are defined on the Web Report node
            (Properties --> Parameters)

        Args:
            nickname (str): Nickname of the Web Reports node.
        Returns:
            Response: List of Web Report parameters. Each list item is a dict describing the parameter.
            Structure of the list items:
            {
                "type": "string",
                "parm_name": "string",
                "display_text": "string",
                "prompt": true,
                "prompt_order": 0,
                "default_value": null,
                "description": "string",
                "mandatory": true
            }
            None if the REST call has failed.
        """

        request_url = self.config()["webReportsUrl"] + "/" + nickname + "/parameters"
        request_header = self.request_form_header()

        logger.debug(
            "Get parameters of Web Report with nickname -> '%s'; calling -> %s",
            nickname,
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get parameters of Web Report with nickname -> '{}'".format(
                nickname
            ),
        )

        if response and "data" in response:
            return response["data"]

        return None

    # end method definition

    def run_web_report(
        self, nickname: str, web_report_parameters: dict | None = None
    ) -> dict | None:
        """Run a Web Report that is identified by its nick name.

        Args:
            nickname (str): nickname of the Web Reports node.
            web_report_parameters (dict): Parameters of the Web Report (names + value pairs)
        Returns:
            dict: Response of the run Web Report request or None if the Web Report execution has failed.
        """

        # Avoid linter warning W0102:
        if web_report_parameters is None:
            web_report_parameters = {}

        request_url = self.config()["webReportsUrl"] + "/" + nickname
        request_header = self.request_form_header()

        logger.debug(
            "Running Web Report with nickname -> %s; calling -> %s",
            nickname,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=web_report_parameters,
            timeout=None,
            failure_message="Failed to run web report with nickname -> '{}'".format(
                nickname
            ),
        )

    # end method definition

    def install_cs_application(self, application_name: str) -> dict | None:
        """Install a CS Application (based on WebReports)

        Args:
            application_name (str): name of the application (e.g. OTPOReports, OTRMReports, OTRMSecReports)
        Returns:
            dict: Response or None if the installation of the CS Application has failed.
        """

        install_cs_application_post_data = {"appName": application_name}

        request_url = self.config()["csApplicationsUrl"] + "/install"
        request_header = self.request_form_header()

        logger.debug(
            "Install CS Application -> '%s'; calling -> %s",
            application_name,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=install_cs_application_post_data,
            timeout=None,
            failure_message="Failed to install CS Application -> '{}'".format(
                application_name
            ),
        )

    # end method definition

    def assign_item_to_user_group(
        self, node_id: int, subject: str, instruction: str, assignees: list
    ) -> dict | None:
        """Assign an Extended ECM item to users and groups. This is a function used by
           Extended ECM for Government.

        Args:
            node_id (int): node ID of the Extended ECM item (e.g. a workspace or a document)
            subject (str): title / subject of the assignment
            instructions (str): more detailed description or instructions for the assignment
            assignees (list): list of IDs of users or groups
        Returns:
            dict: Response of the request or None if the assignment has failed.
        """

        assignment_post_data = {
            "subject": subject,
            "instruction": instruction,
            "assignees": assignees,
        }

        request_url = (
            self.config()["nodesUrlv2"] + "/" + str(node_id) + "/xgovassignments"
        )

        request_header = self.request_form_header()

        logger.debug(
            "Assign item with ID -> %s to assignees -> %s (subject -> '%s'); calling -> %s",
            str(node_id),
            str(assignees),
            subject,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data={"add_assignment": json.dumps(assignment_post_data)},
            timeout=None,
            failure_message="Failed to assign item with ID -> {} to assignees -> {} (subject -> '{}')".format(
                node_id, assignees, subject
            ),
        )

    # end method definition

    def convert_permission_string_to_permission_value(self, permissions: list) -> int:
        """Converts a list of permission names (strongs) to a bit-mask.

        Args:
            permissions (list): List of permission names - see conversion variable below.
        Returns:
            int: bit-encoded permission value
        """

        conversion = {
            "see": 130,  # Bits 2 and 8
            "see_contents": 36865,  # Bit 17
            "modify": 65536,  # Bit 18
            "edit_attributes": 131072,  # Bit 19
            "add_items": 4,  # Bit 3
            "reserve": 8192,  # Bit 14
            "add_major_version": 4194304,  # Bit 23
            "delete_versions": 16384,  # Bit 15
            "delete": 8,  # Bit 4
            "edit_permissions": 16,  # Bit 5
        }

        permission_value = 0

        for permission in permissions:
            if not conversion.get(permission):
                logger.error("Illegal permission value -> %s", str(permission))
                return 0
            permission_value += conversion[permission]

        return permission_value

    # end method definition

    def convert_permission_value_to_permission_string(
        self, permission_value: int
    ) -> list:
        """Converts a bit-encoded permission value to a list of permission names (strings).

        Args:
            permission_value (int): bit-encoded permission value
        Returns:
            list: list of permission names
        """

        conversion = {
            "see": 130,  # Bits 2 and 8
            "see_contents": 36865,  # Bit 17
            "modify": 65536,  # Bit 18
            "edit_attributes": 131072,  # Bit 19
            "add_items": 4,  # Bit 3
            "reserve": 8192,  # Bit 14
            "add_major_version": 4194304,  # Bit 23
            "delete_versions": 16384,  # Bit 15
            "delete": 8,  # Bit 4
            "edit_permissions": 16,  # Bit 5
        }

        permissions = []

        for key, value in conversion.items():
            if permission_value & value:  # binary and
                permissions.append(key)

        return permissions

    # end method definition

    def assign_permission(
        self,
        node_id: int,
        assignee_type: str,
        assignee: int,
        permissions: list,
        apply_to: int = 0,
    ) -> dict | None:
        """Assign permissions for Extended ECM item to a user or group.

        Args:
            node_id (int): node ID of the Extended ECM item
            assignee_type (str): this can be either "owner", "group" (for owner group),
                                    "public", or "custom" (assigned access)
            assignee (int): ID of user or group ("right ID"). If 0 and assigneeType
                                is "owner" or "group" then it is assumed that the owner and
                                owner group should not be changed.
            permissions (list): list of permissions - potential elements:
                                "see"
                                "see_contents"
                                "modify"
                                "edit_attributes"
                                "add_items"
                                "reserve"
                                "add_major_version"
                                "delete_versions"
                                "delete"
                                "edit_permissions"
            apply_to (int, optional): elements to apply permissions to - potential values:
                                 0 = this item (default)
                                 1 = sub-items
                                 2 = This item and sub-items
                                 3 = This item and immediate sub-items
        Returns:
            dict: Response of the request or None if the assignment of permissions has failed.
        """

        if not assignee_type or not assignee_type in [
            "owner",
            "group",
            "public",
            "custom",
        ]:
            logger.error(
                "Missing or wrong assignee type. Needs to be owner, group, public or custom!"
            )
            return None
        if assignee_type == "custom" and not assignee:
            logger.error("Missing permission assignee!")
            return None

        permission_post_data = {
            "permissions": permissions,
            "apply_to": apply_to,
        }

        # Assignees can be specified for owner and group and must be specified for custom:
        #
        if assignee:
            permission_post_data["right_id"] = assignee

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "/permissions/"
            + assignee_type
        )

        request_header = self.request_form_header()

        logger.debug(
            "Assign permissions -> %s to item with ID -> %s; assignee type -> '%s'; calling -> %s",
            str(permissions),
            str(node_id),
            assignee_type,
            request_url,
        )

        if assignee_type == "custom":
            # Custom also has a REST POST - we prefer this one as to
            # also allows to add a new assigned permission (user or group):
            return self.do_request(
                url=request_url,
                method="POST",
                headers=request_header,
                data={"body": json.dumps(permission_post_data)},
                timeout=None,
                failure_message="Failed to assign custom permissions -> {} to item with ID -> {}".format(
                    permissions, node_id
                ),
            )
        else:
            # Owner, Owner Group and Public require REST PUT:
            return self.do_request(
                url=request_url,
                method="PUT",
                headers=request_header,
                data={"body": json.dumps(permission_post_data)},
                timeout=None,
                failure_message="Failed to assign stadard permissions -> {} to item with ID -> {}".format(
                    permissions, node_id
                ),
            )

    # end method definition

    def get_node_categories(self, node_id: int, metadata: bool = True) -> dict | None:
        """Get categories assigned to a node.

        Args:
            node_id (int): ID of the node to get the categories for.
            metadata (bool, optional): expand the attribute definitions of the category. Default is True.
        Returns:
            dict | None: category response or None if the call to the REST API fails.

            Example:
            [
                {
                    'data': {
                        'categories': {
                            '16878_25': 'Customer',
                            '16878_28': '50031',
                            '16878_29': 'Global Trade AG',
                            '16878_30': 'Gutleutstraße 53',
                            '16878_31': 'Germany',
                            '16878_32': '60329',
                            '16878_33': ['1000'],
                            '16878_34': 'Frankfurt',
                            '16878_37': ['Retail'],
                            '16878_38': '0000050031',
                            '16878_39_1_40': '0000001096',
                            '16878_39_1_41': 'Heinz Hart',
                            '16878_39_1_42': 'Purchasing',
                            '16878_39_1_43': 'Purchasing Manager',
                            '16878_39_1_44': '+49695325410',
                            '16878_39_1_45': '+49695325499',
                            '16878_39_1_46': 'Heinz.Hart@GlobalTrade.com',
                            '16878_39_1_47': 'B',
                            '16878_39_1_48': '4',
                            ...
                        }
                    },
                    'metadata': {
                        '16878': {
                            'allow_undefined': False,
                            'bulk_shared': False,
                            'default_value': None,
                            'description': None,
                            'hidden': False,
                            'key': '16878',
                            'key_value_pairs': False,
                            'multi_value': False,
                            'multi_value_length_default': 1,
                            'multi_value_length_fixed': True,
                            'multi_value_length_max': 1,
                            'multi_value_max_length': None,
                            'multi_value_min_length': None,
                            'multi_value_unique': False,
                            'name': 'Customer',
                            'next_id': 83,
                            'persona': 'category',
                            'read_only': True,
                            'required': False,
                            ...
                        },
                        '16878_25': {
                            'allow_undefined': False,
                            'bulk_shared': False,
                            'default_value': None,
                            'description': None,
                            'hidden': False,
                            'key': '16878_25',
                            'key_value_pairs': False,
                            'max_length': None,
                            'min_length': None,
                            'multi_select': False,
                            'multi_value': False,
                            'multi_value_length_default': 1,
                            'multi_value_length_fixed': True,
                            'multi_value_length_max': 1,
                            'multi_value_max_length': None,
                            'multi_value_min_length': None,
                            'multi_value_unique': False,
                            'multiline': False,
                            'multilingual': False,
                            ...
                        },
                        '16878_28': {
                            'allow_undefined': False,
                            'bulk_shared': False,
                            'default_value': None,
                            'description': None,
                            'hidden': False,
                            'key': '16878_28',
                            'key_value_pairs': False,
                            'max_length': 10,
                            'min_length': None,
                            'multi_select': False,
                            'multi_value': False,
                            'multi_value_length_default': 1,
                            'multi_value_length_fixed': True,
                            'multi_value_length_max': 1,
                            'multi_value_max_length': None,
                            'multi_value_min_length': None,
                            'multi_value_unique': False,
                            'multiline': False,
                            'multilingual': False,
                            ...
                        },
                        ...
                    }
                    'metadata_map': {
                        'categories': {'16878': ['16878_2', '16878_3', '16878_4', '16878_5', '16878_6', '16878_7', '16878_8']}
                    }
                    'metadata_order': {
                        'categories': ['16878']
                    }
                }
            ]
        """

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/categories"
        if metadata:
            request_url += "?metadata"
        request_header = self.request_form_header()

        logger.debug(
            "Get categories of node with ID -> %s; calling -> %s",
            str(node_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get categories for node ID -> {}".format(
                str(node_id)
            ),
        )

    # end method definition

    def get_node_category(
        self, node_id: int, category_id: int, metadata: bool = True
    ) -> dict | None:
        """Get a specific category assigned to a node.

        Args:
            node_id (int): ID of the node to get the categories for.
            category_id (int): ID of the category definition ID (in category volume)
            metadata (bool, optional): expand the attribute definitions of the category. Default is True
        Returns:
            dict: category response or None if the call to the REST API fails.
        """

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "/categories/"
            + str(category_id)
        )
        if metadata:
            request_url += "?metadata"
        request_header = self.request_form_header()

        logger.debug(
            "Get category with ID -> %s on node with ID -> %s; calling -> %s",
            str(category_id),
            str(node_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get category with ID -> {} for node ID -> {}".format(
                category_id, node_id
            ),
        )

    # end method definition

    def get_node_category_ids(self, node_id: int) -> list:
        """Get list of all category definition IDs that are assign to the node.

        Args:
            node_id (int): ID of the node to get the categories for.
        Returns:
            list: list of category IDs (all categories assigned to the node)
        """

        categories = self.get_node_categories(node_id)
        if not categories or not categories["results"]:
            return None

        category_id_list = []

        for category in categories["results"]:
            category_id_list += [
                int(i) for i in category["metadata_order"]["categories"]
            ]

        return category_id_list

    # end method definition

    def get_node_category_names(self, node_id: int) -> list | None:
        """Get list of all category names that are assign to the node.

        Args:
            node_id (int): ID of the node to get the categories for.
        Returns:
            list: list of category names (all categories assigned to the node)
        """

        categories = self.get_node_categories(node_id=node_id, metadata=True)
        if not categories or not categories["results"]:
            return None

        # List comprehension to extract category names safely
        return [
            next(iter(category["metadata"]["categories"].values()), {}).get("name")
            for category in categories["results"]
        ]

    # end method definition

    def get_node_category_definition(
        self,
        node_id: int,
        category_name: str,
    ) -> tuple[int, dict]:
        """Get category definition (category id and attribute names, IDs and types).
           This is a convenience method that wraps the the complex return value
           of get_node_categories() in an easier to parse structure.

        Args:
            node_id (int): node to read the category definition from
                           (e.g. a workspace template or a document template or a target folder)
                           This should NOT be the category definition object!
            category_name (str): name of the category
        Returns:
            int: category ID
            dict: dict keys are the attribute names. dict values are sub-dictionaries with the id and type of the attribute.
                  For set attributes the key is constructed as <set name>:<attribute name>.
                  Set attributes also incluide an additional value "set_id".

            Example response:
            {
                'Status': {'id': '16892_25', 'type': 'String'},
                'Customer Number': {'id': '16892_28', 'type': 'String'},
                'Name': {'id': '16892_29', 'type': 'String'},
                'Street': {'id': '16892_30', 'type': 'String'},
                'Country': {'id': '16892_31', 'type': 'String'},
                'Postal code': {'id': '16892_32', 'type': 'String'},
                'Sales organisation': {'id': '16892_33', 'type': 'String'},
                'City': {'id': '16892_34', 'type': 'String'},
                'Industry': {'id': '16892_37', 'type': 'String'},
                'Object Key': {'id': '16892_38', 'type': 'String'},
                'Contacts': {'id': '16892_39', 'type': 'set'},
                'Contacts:BP No': {'id': '16892_39_x_40', 'type': 'String', 'set_id': '16892_39'},
                'Contacts:Name': {'id': '16892_39_x_41', 'type': 'String', 'set_id': '16892_39'},
                'Contacts:Department': {'id': '16892_39_x_42', 'type': 'String', 'set_id': '16892_39'},
                'Contacts:Function': {'id': '16892_39_x_43', 'type': 'String', 'set_id': '16892_39'},
                'Contacts:Phone': {'id': '16892_39_x_44', 'type': 'String', 'set_id': '16892_39'},
                'Contacts:Fax': {'id': '16892_39_x_45', 'type': 'String', 'set_id': '16892_39'},
                'Contacts:Email': {'id': '16892_39_x_46', 'type': 'String', 'set_id': '16892_39'},
                'Contacts:Building': {'id': '16892_39_x_47', 'type': 'String', 'set_id': '16892_39'},
                'Contacts:Floor': {'id': '16892_39_x_48', 'type': 'String', 'set_id': '16892_39'},
                'Contacts:Room': {'id': '16892_39_x_49', 'type': 'String', 'set_id': '16892_39'},
                'Contacts:Comments': {'id': '16892_39_x_50', 'type': 'String', 'set_id': '16892_39'},
                'Contacts:Valid from': {'id': '16892_39_x_51', 'type': 'Date', 'set_id': '16892_39'},
                'Contacts:Valid to': {'id': '16892_39_x_52', 'type': 'Date', 'set_id': '16892_39'},
                'Sales Areas': {'id': '16892_53', 'type': 'set'},
                'Sales Areas:Sales Organisation': {'id': '16892_53_x_54', 'type': 'String', 'set_id': '16892_53'},
                'Sales Areas:Distribution Channel': {'id': '16892_53_x_55', 'type': 'String', 'set_id': '16892_53'},
                'Sales Areas:Division': {'id': '16892_53_x_56', 'type': 'String', 'set_id': '16892_53'},
                'Rating': {'id': '16892_57', 'type': 'set'},
                'Rating:Credit Standing': {'id': '16892_57_x_58', 'type': 'String', 'set_id': '16892_57'},
                'Rating:Date': {'id': '16892_57_x_59', 'type': 'Date', 'set_id': '16892_57'},
                'Rating:Status': {'id': '16892_57_x_60', 'type': 'String', 'set_id': '16892_57'},
                'Rating:add. Information': {'id': '16892_57_x_61', 'type': 'String', 'set_id': '16892_57'},
                'Rating:Institute': {'id': '16892_57_x_62', 'type': 'String', 'set_id': '16892_57'},
                'Rating:Rating': {'id': '16892_57_x_63', 'type': 'String', 'set_id': '16892_57'},
                'Locations': {'id': '16892_75', 'type': 'set'},
                'Locations:Type': {'id': '16892_75_x_76', 'type': 'String', 'set_id': '16892_75'},
                'Locations:Street': {'id': '16892_75_x_77', 'type': 'String', 'set_id': '16892_75'},
                'Locations:City': {'id': '16892_75_x_78', 'type': 'String', 'set_id': '16892_75'},
                'Locations:Country': {'id': '16892_75_x_79', 'type': 'String', 'set_id': '16892_75'},
                'Locations:Postal code': {'id': '16892_75_x_80', 'type': 'String', 'set_id': '16892_75'},
                'Locations:Valid from': {'id': '16892_75_x_81', 'type': 'Date', 'set_id': '16892_75'},
                'Locations:Valid to': {'id': '16892_75_x_82', 'type': 'Date', 'set_id': '16892_75'}
            }
        """

        attribute_definitions = {}

        response = self.get_node_categories(node_id)
        if response and response["results"]:
            for categories in response["results"]:
                # get all metadata IDs
                keys = categories["metadata"]["categories"].keys()
                # There's one without an underscore - that's the ID of the category itself:
                cat_id = next((key for key in keys if "_" not in key), -1)
                cat_name = categories["metadata"]["categories"][cat_id]["name"]
                # Check we have the category we are looking for:
                if cat_name != category_name:
                    # Wrong category - not matching - go to next
                    continue
                for att_id in categories["metadata"]["categories"]:
                    if not "_" in att_id:
                        # We skip the element representing the category itself:
                        continue
                    att_name = categories["metadata"]["categories"][att_id]["name"]
                    att_persona = categories["metadata"]["categories"][att_id][
                        "persona"
                    ]
                    # Persona can be either "set" or "categoryattribute".
                    # If the persona is "set" we store the set information:
                    if att_persona == "set":
                        # We save the set name and ID for the attributes that follow:
                        set_name = att_name
                        set_id = att_id
                    # Attribute types can be "String", ...
                    # For the set attribute itself the type_name = "Assoc"
                    att_type = categories["metadata"]["categories"][att_id]["type_name"]
                    if "_x_" in att_id:  # this is not true for the set attribute itself
                        # set_name and set_id are still set to the name of the proceeding
                        # for-loop iteration!
                        attribute_definitions[set_name + ":" + att_name] = {
                            "id": att_id,
                            "type": att_type,
                            "set_id": set_id,
                        }
                    else:
                        attribute_definitions[att_name] = {
                            "id": att_id,
                            "type": att_type,
                        }

                return cat_id, attribute_definitions
        return -1, {}

    # end method definition

    def assign_category(
        self,
        node_id: int,
        category_id: list,
        inheritance: bool = False,
        apply_to_sub_items: bool = False,
        apply_action: str = "add_upgrade",
        add_version: bool = False,
        clear_existing_categories: bool = False,
    ) -> bool:
        """Assign a category to a node. Optionally turn on inheritance and apply
           category to sub-items (if node_id is a container / folder / workspace).
           If the category is already assigned to the node this method will
           throw an error.

        Args:
            node_id (int): node ID to apply the category to
            category_id (list): ID of the category definition object
            inheritance (bool): turn on inheritance for the category
                                (this makes only sense if the node is a container like a folder or workspace)
            apply_to_sub_items (bool, optional): if True the category is applied to
                                                    the item and all its sub-items
                                                    if False the category is only applied
                                                    to the item
            apply_action (str, optional): supported values are "add", "add_upgrade", "upgrade", "replace", "delete", "none", None
            add_version (bool, optional): if a document version should be added for the category change (default = False)
            clear_existing_categories (bool, optional): whether or not existing (other) categories should be removed (default = False)
        Returns:
            bool: True = success, False = error
        """

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/categories"
        request_header = self.request_form_header()

        #
        # 1. Assign Category to Node if not yet assigned:
        #

        existing_category_ids = self.get_node_category_ids(node_id)
        if not category_id in existing_category_ids:
            logger.debug(
                "Category with ID -> %s is not yet assigned to node ID -> %s. Assigning it now...",
                str(category_id),
                str(node_id),
            )
            category_post_data = {
                "category_id": category_id,
            }

            logger.debug(
                "Assign category with ID -> %s to item with ID -> %s; calling -> %s",
                str(category_id),
                str(node_id),
                request_url,
            )

            response = self.do_request(
                url=request_url,
                method="POST",
                headers=request_header,
                data=category_post_data,
                timeout=None,
                failure_message="Failed to assign category with ID -> {} to node with ID -> {}".format(
                    category_id, node_id
                ),
                parse_request_response=False,
            )

            if not response or not response.ok:
                return False

        #
        # 2. Set Inheritance
        #

        response = self.set_category_inheritance(
            node_id=node_id, category_id=category_id, enable=inheritance
        )
        if not response:
            return False

        #
        # 3. Apply to sub-items
        #

        if apply_to_sub_items:
            request_url_apply_sub_items = request_url + "/apply"

            category_post_data = {
                "categories": [{"id": category_id, "action": apply_action}],
                "add_version": add_version,
                "clear_existing_categories": clear_existing_categories,
            }

            # we need to wrap the body of this POST call into a "body"
            # tag. This is documented worngly on developer.opentext.com
            response = self.do_request(
                url=request_url_apply_sub_items,
                method="POST",
                headers=request_header,
                data={"body": json.dumps(category_post_data)},
                timeout=None,
                failure_message="Failed to apply category with ID -> {} to sub-items of node with ID -> {}".format(
                    category_id, node_id
                ),
                parse_request_response=False,
            )

            if not response or not response.ok:
                return False

        return True

    # end method definition

    def get_category_value_by_name(
        self,
        node_id: int,
        category_name: str,
        attribute_name: str,
        set_name: str | None = None,
        set_row: int = 1,
    ) -> str | list | None:
        """Lookup the value of an attribute if category name, set name and attribute name
           are known.

        Args:
            node_id (int): ID of the node the category is assigned to.
            category_name (str): Name of the category.
            attribute_name (str): Name of the attribute.
            set_name (str | None, optional): Name of the set. Defaults to None.
            set_row (int, optional): Index of the row (first row = 1!). Defaults to 1.

        Returns:
            str | list | None: The value of the attribute. If it is a multi-value attribute a list will be returned.
        """

        (_, cat_definitions) = self.get_node_category_definition(node_id, category_name)
        if not cat_definitions:
            logger.warning("No categories are assigned to node -> %s", str(node_id))
            return None

        if set_name:
            lookup = set_name + ":" + attribute_name
        else:
            lookup = attribute_name

        if not lookup in cat_definitions:
            logger.error("Cannot find attribute -> '%s' in category -> '%s'")

        att_def = cat_definitions[lookup]
        att_id = att_def["id"]
        if "_x_" in att_id:
            att_id = att_id.replace("_x_", "_" + str(set_row) + "_")

        value = None

        response = self.get_node_categories(node_id=node_id, metadata=False)
        categories = response["results"]
        for category in categories:
            if att_id in category["data"]["categories"]:
                value = category["data"]["categories"][att_id]
                break

        return value

    # end method definition

    def get_category_value(
        self,
        node_id: int,
        category_id: int,
        attribute_id: int,
        set_id: int | None = None,
        set_row: int = 1,
    ) -> str | list | None:
        """Lookup the value of an attribute if category ID, set ID and attribute ID
           are known. If you only have the names use get_category_value_by_name()

        Args:
            node_id (int): Node ID the category is assigned to
            category_id (int): ID of the category
            attribute_id (int): ID of the attribute (the pure ID without underscores)
            set_id (int, optional): ID of the set. Defaults to None.
            set_row (int, optional): Index of the row (first row = 1!). Defaults to 1.

        Returns:
            str | list | None: The value of the attribute. If it is a multi-value attribute a list will be returned.
        """

        if set_id and set_row:
            att_id = (
                str(category_id)
                + "_"
                + str(set_id)
                + "_"
                + str(set_row)
                + "_"
                + str(attribute_id)
            )
        elif set_id:
            att_id = str(category_id) + "_" + str(set_id) + "_" + str(attribute_id)
        else:
            att_id = str(category_id) + "_" + str(attribute_id)

        response = self.get_node_categories(node_id=node_id, metadata=False)
        categories = response["results"]

        value = None

        for category in categories:
            if att_id in category["data"]["categories"]:
                value = category["data"]["categories"][att_id]
                break

        return value

    # end method definition

    def set_category_value(
        self,
        node_id: int,
        value,
        category_id: int,
        attribute_id: int,
        set_id: int = 0,
        set_row: int = 1,
    ) -> dict | None:
        """Set a value to a specific attribute in a category. Categories and have sets (groupings), multi-line sets (matrix),
           and multi-value attributes (list of values). This method supports all variants.

        Args:
            node_id (int): ID of the node
            value (multi-typed): value to be set - can be string or list of strings (for multi-value attributes)
            category_id (int):ID of the category object
            attribute_id (int): ID of the attribute, this should not include the category ID nor an underscore but the plain attribute ID like '10'
            set_id (int, optional): ID of the set. Defaults to 0.
            set_row (int, optional): Row of . Defaults to 1.

        Returns:
            dict: REST API response or None if the call fails
        """

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "/categories/"
            + str(category_id)
        )
        request_header = self.request_form_header()

        if set_id:
            logger.debug(
                "Assign value -> '%s' to category with ID -> %s, set ID -> %s, row -> %s, attribute ID -> %s on node with ID -> %s; calling -> %s",
                str(value),
                str(category_id),
                str(set_id),
                str(set_row),
                str(attribute_id),
                str(node_id),
                request_url,
            )
            category_put_data = {
                "category_id": category_id,
                "{}_{}_{}_{}".format(category_id, set_id, set_row, attribute_id): value,
            }
            failure_message = "Failed to set value -> '{}' for category with ID -> {}, set ID -> {}, set row -> {}, attribute ID -> {} on node ID -> {}".format(
                value,
                category_id,
                set_id,
                set_row,
                attribute_id,
                node_id,
            )
        else:
            logger.debug(
                "Assign value -> '%s' to category ID -> %s, attribute ID -> %s on node with ID -> %s; calling -> %s",
                str(value),
                str(category_id),
                str(attribute_id),
                str(node_id),
                request_url,
            )
            category_put_data = {
                "category_id": category_id,
                "{}_{}".format(category_id, attribute_id): value,
            }
            failure_message = "Failed to set value -> '{}' for category with ID -> {}, attribute ID -> {} on node ID -> {}".format(
                value,
                category_id,
                attribute_id,
                node_id,
            )

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data=category_put_data,
            timeout=None,
            failure_message=failure_message,
        )

    # end method definition

    def set_category_values(
        self,
        node_id: int,
        category_id: int,
        category_data: dict,
    ) -> dict | None:
        """Set values of a category. Categories and have sets (groupings), multi-line sets (matrix),
           and multi-value attributes (list of values). This method supports all variants.

        Args:
            node_id (int): ID of the node
            value (multi-typed): value to be set - can be string or list of strings (for multi-value attributes)
            category_id (int):ID of the category object
            category_data (dict): dictionary with category attributes and values

        Returns:
            dict: REST API response or None if the call fails
        """

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "/categories/"
            + str(category_id)
        )
        request_header = self.request_form_header()

        category_put_data = {"category_id": category_id}
        category_put_data.update(category_data)

        logger.debug(
            "Set values -> %s for category ID -> %s on node -> %s...",
            category_data,
            category_id,
            node_id,
        )

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data=category_put_data,
            timeout=None,
            failure_message="Failed to set values -> '{}' for category with ID -> {}, on node ID -> {}".format(
                category_data, category_id, node_id
            ),
        )

    # end method definition

    def set_category_inheritance(
        self, node_id: int, category_id: int, enable: bool = True
    ) -> dict | None:
        """Set if we want a container item (e.g. a folder or workspace) to inherit
           categories to sub-items.

        Args:
            node_id (int): Node ID of the container item.
            category_id (int): Node ID of the category item.
            enable (bool): Whether the inheritance should be enabled (True) or disabled (False)

        Returns:
            dict | None: Response of the request or None in case of an error.
        """

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "/categories/"
            + str(category_id)
            + "/inheritance"
        )
        request_header = self.request_form_header()

        if enable:
            logger.debug(
                "Enable category inheritance for node with ID -> %s and category ID -> %s; calling -> %s",
                str(node_id),
                str(category_id),
                request_url,
            )
            return self.do_request(
                url=request_url,
                method="POST",
                headers=request_header,
                timeout=None,
                failure_message="Failed to enable categories inheritance for node ID -> {} and category ID -> {}".format(
                    node_id, category_id
                ),
            )
        else:
            logger.debug(
                "Disable category inheritance of node with ID -> %s and category ID -> %s; calling -> %s",
                str(node_id),
                str(category_id),
                request_url,
            )
            return self.do_request(
                url=request_url,
                method="DELETE",
                headers=request_header,
                timeout=None,
                failure_message="Failed to disable categories inheritance for node ID -> {} and category ID -> {}".format(
                    node_id, category_id
                ),
            )

    # end method definition

    def assign_classification(
        self, node_id: int, classifications: list, apply_to_sub_items: bool = False
    ) -> dict | None:
        """Assign one or multiple classifications to an Extended ECM item

        Args:
            node_id (int): node ID of the Extended ECM item
            classifications (list): list of classification item IDs
            apply_to_sub_items (bool, optional): if True the classification is applied to
                                                    the item and all its sub-items
                                                    if False the classification is only applied
                                                    to the item
        Returns:
            dict: Response of the request or None if the assignment of the classification has failed.
        """

        # the REST API expects a list of dict elements with "id" and the actual IDs
        classification_list = []
        for classification in classifications:
            classification_list.append({"id": classification})

        classification_post_data = {
            "class_id": classification_list,
            "apply_to_sub_items": apply_to_sub_items,
        }

        request_url = (
            self.config()["nodesUrl"] + "/" + str(node_id) + "/classifications"
        )

        request_header = self.request_form_header()

        logger.debug(
            "Assign classifications with IDs -> %s to item with ID -> %s; calling -> %s",
            str(classifications),
            str(node_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=classification_post_data,
            timeout=None,
            failure_message="Failed to assign classifications with IDs -> {} to item with ID -> {}".format(
                classifications, node_id
            ),
        )

    # end method definition

    def assign_rm_classification(
        self, node_id: int, rm_classification: int, apply_to_sub_items: bool = False
    ) -> dict | None:
        """Assign a RM classification to an Extended ECM item
        Args:
            node_id (int): node ID of the Extended ECM item
            rm_classification (int): Records Management classification ID
            apply_to_sub_items (bool, optional): if True the RM classification is applied to
                                                    the item and all its sub-items
                                                    if False the RM classification is only applied
                                                    to the item
        Returns:
            dict: Response of the request or None if the assignment of the RM classification has failed.
        """

        rm_classification_post_data = {
            "class_id": rm_classification,
            "apply_to_sub_items": apply_to_sub_items,
        }

        request_url = (
            self.config()["nodesUrl"] + "/" + str(node_id) + "/rmclassifications"
        )

        request_header = self.request_form_header()

        logger.debug(
            "Assign RM classifications with ID -> %s to item with ID -> %s; calling -> %s",
            str(rm_classification),
            str(node_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=rm_classification_post_data,
            timeout=None,
            failure_message="Failed to assign RM classifications with ID -> {} to item with ID -> {}".format(
                rm_classification, node_id
            ),
        )

    # end method definition

    def register_workspace_template(self, node_id: int) -> dict | None:
        """Register a workspace template as project template for Extended ECM for Engineering

        Args:
            node_id (int): node ID of the Extended ECM workspace template
        Returns:
            dict: Response of request or None if the registration of the workspace template has failed.
        """

        registration_post_data = {"ids": "{{ {} }}".format(node_id)}

        request_url = self.config()["xEngProjectTemplateUrl"]

        request_header = self.request_form_header()

        logger.debug(
            "Register workspace template with ID -> %s for Extended ECM for Engineering; calling -> %s",
            str(node_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=registration_post_data,
            timeout=None,
            failure_message="Failed to register Workspace Template with ID -> {} for Extended ECM for Engineering".format(
                node_id
            ),
        )

    # end method definition

    def get_records_management_rsis(self, limit: int = 100) -> list | None:
        """Get all Records management RSIs togther with their RSI Schedules.

        Args:
            limit (int, optional): max elements to return (default = 100)
        Returns:
            list: list of Records Management RSIs or None if the request fails.
            Each RSI list element is a dict with this structure:
            {
                "RSIID": 0,
                "RSI": "string",
                "Title": "string",
                "Subject": "string",
                "Description": "string",
                "CreateDate": "string",
                "RSIStatus": "string",
                "StatusDate": "string",
                "DiscontFlag": 0,
                "DiscontDate": "string",
                "DiscontComment": "string",
                "Active": 0,
                "DispControl": 0,
                "RSIScheduleID": 0,
                "RetStage": "string",
                "RecordType": 0,
                "EventType": 0,
                "RSIRuleCode": "string",
                "DateToUse": "string",
                "YearEndMonth": 0,
                "YearEndDay": 0,
                "RetYears": 0,
                "RetMonths": 0,
                "RetDays": 0,
                "RetIntervals": 0,
                "EventRuleDate": "string",
                "EventRule": "string",
                "EventComment": "string",
                "StageAction": "string",
                "FixedRet": 0,
                "ActionCode": "string",
                "ActionDescription": "string",
                "Disposition": "string",
                "ApprovalFlag": 0,
                "MaximumRet": 0,
                "ObjectType": "LIV"
            }
        """

        request_url = self.config()["rsisUrl"] + "?limit=" + str(limit)
        request_header = self.request_form_header()

        logger.debug("Get list of Records Management RSIs; calling -> %s", request_url)

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get list of Records Management RSIs",
        )

        if response and "results" in response and response["results"]:
            return response["results"]["data"]["rsis"]

        return None

    # end method definition

    def get_records_management_codes(self) -> dict | None:
        """Get Records Management Codes. These are the most basic data types of
           the Records Management configuration and required to create RSIs and
           other higher-level Records Management configurations

        Args:
            None
        Returns:
            dict: RM codes or None if the request fails.
        """

        request_url = self.config()["recordsManagementUrlv2"] + "/rmcodes"
        request_header = self.request_form_header()

        logger.debug("Get list of Records Management codes; calling -> %s", request_url)

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get list of Records Management codes",
        )

        if response and "results" in response and response["results"]:
            return response["results"]["data"]

        return None

    # end method definition

    # This is not yet working. REST API endpoint seems not to be in 22.4. Retest with 23.1
    def update_records_management_codes(self, rm_codes: dict) -> dict | None:
        """Update Records Management Codes. These are the most basic data types of
           the Records Management configuration and required to create RSIs and
           other higher-level Records Management configurations
           THIS METHOD IS CURRENTLY NOT WORKING

        Args:
            rm_codes (dict): Codes to be updated
        Returns:
            dict: RSI data or None if the request fails.
        """

        update_rm_codes_post_data = {}

        request_url = self.config()["recordsManagementUrl"] + "/rmcodes"
        request_header = self.request_form_header()

        logger.debug(
            "Update Records Management codes -> %s; calling -> %s",
            str(rm_codes),
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=update_rm_codes_post_data,
            timeout=None,
            failure_message="Failed to update Records Management codes with -> {}".format(
                rm_codes
            ),
        )

        if response and "results" in response and response["results"]:
            return response["results"]["data"]

        return None

    # end method definition

    def create_records_management_rsi(
        self,
        name: str,
        status: str,
        status_date: str,
        description: str,
        subject: str,
        title: str,
        dispcontrol: bool,
    ) -> dict | None:
        """Create a new Records Management RSI.

        Args:
            name (str): name of the RSI
            status (str): status of the RSI
            status_date (str): statusDate of the RSI YYYY-MM-DDTHH:mm:ss
            description (str): description of the RSI
            subject (str): status of the RSI
            title (str): status of the RSI
            dispcontrol (bool): status of the RSI
        Returns:
            dict: RSI data or None if the request fails.
        """

        if status_date == "":
            now = datetime.now()
            status_date = now.strftime("%Y-%m-%dT%H:%M:%S")

        create_rsi_post_data = {
            "name": name,
            "status": status,
            "statusDate": status_date,
            "description": description,
            "subject": subject,
            "title": title,
            "dispcontrol": dispcontrol,
        }

        request_url = self.config()["rsiSchedulesUrl"]

        request_header = self.request_form_header()

        logger.debug(
            "Create Records Management RSI -> %s; calling -> %s", name, request_url
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=create_rsi_post_data,
            timeout=None,
            failure_message="Failed to create Records Management RSI -> '{}'".format(
                name
            ),
        )

    # end method definition

    def create_records_management_rsi_schedule(
        self,
        rsi_id: int,
        stage: str,
        event_type: int = 1,
        object_type: str = "LIV",
        rule_code: str = "",
        rule_comment: str = "",
        date_to_use: int = 91,
        retention_years: int = 0,
        retention_months: int = 0,
        retention_days: int = 0,
        category_id: int = 0,
        attribute_id: int = 0,
        year_end_month: int = 12,
        year_end_day: int = 31,
        retention_intervals: int = 1,
        fixed_retention: bool = True,
        maximum_retention: bool = True,
        fixed_date: str = "",
        event_condition: str = "",
        disposition: str = "",
        action_code: int = 0,
        description: str = "",
        new_status: str = "",
        min_num_versions_to_keep: int = 1,
        purge_superseded: bool = False,
        purge_majors: bool = False,
        mark_official_rendition: bool = False,
    ) -> dict | None:
        """Create a new Records Management RSI Schedule for an existing RSI.

        Args:
            rsi_id (int): ID of an existing RSI the schedule should be created for
            stage (str): retention stage - this is the key parameter to define multiple stages (stages are basically schedules)
            event_type (int): 1 Calculated Date, 2 Calendar Calculation, 3 Event Based, 4 Fixed Date, 5 Permanent
            object_type (str): either "LIV" - Classified Objects (default) or "LRM" - RM Classifications
            rule_code (str, optional): rule code - this value must be defined upfront
            rule_comment (str, optional): comment for the rule
            date_to_use (int, optional): 91 Create Date, 92 Reserved Data, 93 Modification Date, 94 Status Date, 95 Records Date
            retention_years (int, optional): years to wait before disposition
            retention_months (int, optional): month to wait before disposition
            retention_days (int, optional): days to wait before disposition
            category_id (int, optional): ID of the category
            attribute_id (int, optional): ID of the category attribute
            year_end_month (int, optional): month the year ends (default = 12)
            year_end_day (int, optional): day the year ends (default = 31)
            retention_intervals (int, optional): retention intervals
            fixed_retention (bool, optional): fixedRetention
            maximum_retention (bool,optional): maximumRetention
            fixed_date(str, optional): fixed date format : YYYY-MM-DDTHH:mm:ss
            event_condition (str, optional): eventCondition
            disposition (str, optional): disposition
            action_code (int, optional): 0 None, 1 Change Status, 7 Close, 8 Finalize Record, 9 Mark Official, 10 Export, 11 Update Storage Provider, 12 Delete Electronic Format, 15 Purge Versions, 16 Make Rendition, 32 Destroy
            description (str, optional): description
            new_status (str, optional): new status
            min_num_versions_to_keep (int, optional): minimum document versions to keep, . Default is 1.
            purge_superseded (bool, optional): purge superseded. Default is False.
            purge_majors (bool, optional): purge majors. Default is False.
            mark_official_rendition (bool, optional): mark official rendition. Default is False.
        Returns:
            dict: RSI Schedule data or None if the request fails.
        """

        if fixedDate == "":
            now = datetime.now()
            fixedDate = now.strftime("%Y-%m-%dT%H:%M:%S")

        create_rsi_schedule_post_data = {
            "objectType": object_type,
            "stage": stage,
            "eventType": event_type,
            "ruleCode": rule_code,
            "ruleComment": rule_comment,
            "dateToUse": date_to_use,
            "retentionYears": retention_years,
            "retentionMonths": retention_months,
            "retentionDays": retention_days,
            "categoryId": category_id,
            "attributeId": attribute_id,
            "yearEndMonth": year_end_month,
            "yearEndDay": year_end_day,
            "retentionIntervals": retention_intervals,
            "fixedRetention": fixed_retention,
            "maximumRetention": maximum_retention,
            "fixedDate": fixed_date,
            "eventCondition": event_condition,
            "disposition": disposition,
            "actionCode": action_code,
            "description": description,
            "newStatus": new_status,
            "minNumVersionsToKeep": min_num_versions_to_keep,
            "purgeSuperseded": purge_superseded,
            "purgeMajors": purge_majors,
            "markOfficialRendition": mark_official_rendition,
        }

        request_url = self.config()["rsiSchedulesUrl"] + "/" + str(rsi_id) + "/stages"

        request_header = self.request_form_header()

        logger.debug(
            "Create Records Management RSI Schedule -> %s for RSI -> %s; calling -> %s",
            stage,
            str(rsi_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=create_rsi_schedule_post_data,
            timeout=None,
            failure_message="Failed to create Records Management RSI Schedule -> '{}' for RSI -> {}".format(
                stage, rsi_id
            ),
        )

    # end method definition

    def create_records_management_hold(
        self,
        hold_type: str,
        name: str,
        comment: str,
        alternate_id: str = "",
        parent_id: int = 0,
        date_applied: str = "",
        date_to_remove: str = "",
    ) -> dict | None:
        """Create a new Records Management Hold.

        Args:
            hold_type (str): type of the Hold
            name (str): name of the RSI
            comment (str): comment
            alternate_id (str, optional): alternate hold ID
            parent_id (int, optional): ID of the parent node. If parent_id is 0 the item will be created right under "Hold Management" (top level item)
            date_applied (str, optional): create date of the Hold in this format: YYYY-MM-DDTHH:mm:ss
            date_to_remove (str, optional): suspend date of the Hold in this format: YYYY-MM-DDTHH:mm:ss
        Returns:
            dict: Hold data or None if the request fails. The dict structure is this: {'holdID': <ID>}
        """

        if date_applied == "":
            now = datetime.now()
            date_applied = now.strftime("%Y-%m-%dT%H:%M:%S")

        create_hold_post_data = {
            "type": hold_type,
            "name": name,
            "comment": comment,
            "date_applied": date_applied,
            "date_to_remove": date_to_remove,
            "alternate_id": alternate_id,
        }

        if parent_id > 0:
            create_hold_post_data["parent_id"] = parent_id

        request_url = self.config()["holdsUrl"]

        request_header = self.request_form_header()

        logger.debug(
            "Create Records Management Hold -> %s; calling -> %s", name, request_url
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=create_hold_post_data,
            timeout=None,
            failure_message="Failed to create Records Management Hold -> '{}'".format(
                name
            ),
        )

    # end method definition

    def get_records_management_holds(self) -> dict | None:
        """Get a list of all Records Management Holds in the system. Even though there are folders
        in the holds management area in RM these are not real folders - they cannot be retrieved
        with get_node_by_parent_and_name() thus we need this method to get them all.

        Args:
            None
        Returns:
            dict: Response with list of holds:
            "results": {
                "data": {
                    "holds": [
                        {
                            "HoldID": 0,
                            "HoldName": "string",
                            "ActiveHold": 0,
                            "OBJECT": 0,
                            "ApplyPatron": "string",
                            "DateApplied": "string",
                            "HoldComment": "string",
                            "HoldType": "string",
                            "DateToRemove": "string",
                            "DateRemoved": "string",
                            "RemovalPatron": "string",
                            "RemovalComment": "string",
                            "EditDate": "string",
                            "EditPatron": "string",
                            "AlternateHoldID": 0,
                            "ParentID": 0
                        }
                    ]
                }
            }
        """

        request_url = self.config()["holdsUrlv2"]

        request_header = self.request_form_header()

        logger.debug("Get list of Records Management Holds; calling -> %s", request_url)

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get list of Records Management Holds",
        )

    # end method definition

    def import_records_management_settings(self, file_path: str) -> bool:
        """Import Records Management settings from a file that is uploaded from the python pod

        Args:
            file_path (str): path + filename of config file in Python container filesystem
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["recordsManagementUrl"] + "/importSettings"

        # When we upload files using the 'files' parameter, the request must be encoded
        # as multipart/form-data, which allows binary data (like files) to be sent along
        # with other form data.
        # The requests library sets this header correctly if the 'files' parameter is provided.
        # So we just put the cookie in the header and trust the request library to add
        # the Content-Type = multipart/form-data :
        request_header = self.cookie()

        logger.debug(
            "Importing Records Management Settings from file -> '%s'; calling -> %s",
            file_path,
            request_url,
        )

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> '%s' does not exist in path -> '%s'!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            files=settings_post_file,
            timeout=None,
            failure_message="Failed to import Records Management Settings from file -> '{}'".format(
                file_path
            ),
            parse_request_response=False,
        )

        if response and response.ok:
            return True

        return False

    # end method definition

    def import_records_management_codes(
        self, file_path: str, update_existing_codes: bool = True
    ) -> bool:
        """Import RM Codes from a file that is uploaded from the python pod

        Args:
            file_path (str): path + filename of settings file in Python container filesystem
            update_existing_codes (bool): Flag that controls whether existing table maintenance codes
                                          should be updated.
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["recordsManagementUrl"] + "/importCodes"

        # When we upload files using the 'files' parameter, the request must be encoded
        # as multipart/form-data, which allows binary data (like files) to be sent along
        # with other form data.
        # The requests library sets this header correctly if the 'files' parameter is provided.
        # So we just put the cookie in the header and trust the request library to add
        # the Content-Type = multipart/form-data :
        request_header = self.cookie()

        logger.debug(
            "Importing Records Management Codes from file -> '%s'; calling -> %s",
            file_path,
            request_url,
        )

        settings_post_data = {"updateExistingCodes": update_existing_codes}

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> '%s' does not exist in path -> '%s'!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=settings_post_data,
            files=settings_post_file,
            timeout=None,
            failure_message="Failed to import Records Management Codes from file -> '{}'".format(
                file_path
            ),
            parse_request_response=False,
        )

        if response and response.ok:
            return True

        return False

    # end method definition

    def import_records_management_rsis(
        self,
        file_path: str,
        update_existing_rsis: bool = True,
        delete_schedules: bool = False,
    ) -> bool:
        """Import RM RSIs from a config file that is uploaded from the Python pod

        Args:
            file_path (str): path + filename of config file in Python container filesystem
            update_existing_rsis (bool, optional): whether or not existing RSIs should be updated (or ignored)
            delete_schedules (bool, optional): whether RSI Schedules should be deleted
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["recordsManagementUrl"] + "/importRSIs"

        # When we upload files using the 'files' parameter, the request must be encoded
        # as multipart/form-data, which allows binary data (like files) to be sent along
        # with other form data.
        # The requests library sets this header correctly if the 'files' parameter is provided.
        # So we just put the cookie in the header and trust the request library to add
        # the Content-Type = multipart/form-data :
        request_header = self.cookie()

        logger.debug(
            "Importing Records Management RSIs from file -> '%s'; calling -> %s",
            file_path,
            request_url,
        )

        settings_post_data = {
            "updateExistingRSIs": update_existing_rsis,
            "deleteSchedules": delete_schedules,
        }

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> '%s' does not exist in path -> '%s'!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=settings_post_data,
            files=settings_post_file,
            timeout=None,
            failure_message="Failed to import Records Management RSIs from file -> '{}'".format(
                file_path
            ),
            parse_request_response=False,
        )

        if response and response.ok:
            return True

        return False

    # end method definition

    def import_physical_objects_settings(self, file_path: str) -> bool:
        """Import Physical Objects settings from a config file that is uploaded from the python pod

        Args:
            file_path (str): path + filename of config file in Python container filesystem
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["physicalObjectsUrl"] + "/importSettings"

        # When we upload files using the 'files' parameter, the request must be encoded
        # as multipart/form-data, which allows binary data (like files) to be sent along
        # with other form data.
        # The requests library sets this header correctly if the 'files' parameter is provided.
        # So we just put the cookie in the header and trust the request library to add
        # the Content-Type = multipart/form-data :
        request_header = self.cookie()

        logger.debug(
            "Importing Physical Objects Settings from server file -> '%s'; calling -> %s",
            file_path,
            request_url,
        )

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> '%s' does not exist in path -> '%s'!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            files=settings_post_file,
            timeout=None,
            failure_message="Failed to import Physical Objects settings from file -> '{}'".format(
                file_path
            ),
            parse_request_response=False,
        )

        if response and response.ok:
            return True

        return False

    # end method definition

    def import_physical_objects_codes(
        self, file_path: str, update_existing_codes: bool = True
    ) -> bool:
        """Import Physical Objects codes from a config file that is uploaded from the Python pod

        Args:
            file_path (str): path + filename of config file in Python container filesystem
            update_existing_codes (bool): whether or not existing codes should be updated (default = True)
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["physicalObjectsUrl"] + "/importCodes"

        # When we upload files using the 'files' parameter, the request must be encoded
        # as multipart/form-data, which allows binary data (like files) to be sent along
        # with other form data.
        # The requests library sets this header correctly if the 'files' parameter is provided.
        # So we just put the cookie in the header and trust the request library to add
        # the Content-Type = multipart/form-data :
        request_header = self.cookie()

        logger.debug(
            "Importing Physical Objects Codes from file -> '%s'; calling -> %s",
            file_path,
            request_url,
        )

        settings_post_data = {"updateExistingCodes": update_existing_codes}

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> '%s' does not exist in path -> '%s'!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=settings_post_data,
            files=settings_post_file,
            timeout=None,
            failure_message="Failed to import Physical Objects Codes from file -> '{}'".format(
                file_path
            ),
            parse_request_response=False,
        )

        if response and response.ok:
            return True

        return False

    # end method definition

    def import_physical_objects_locators(self, file_path: str) -> bool:
        """Import Physical Objects locators from a config file that is uploaded from the python pod

        Args:
            file_path (str): path + filename of config file in Python container filesystem
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["physicalObjectsUrl"] + "/importLocators"

        # When we upload files using the 'files' parameter, the request must be encoded
        # as multipart/form-data, which allows binary data (like files) to be sent along
        # with other form data.
        # The requests library sets this header correctly if the 'files' parameter is provided.
        # So we just put the cookie in the header and trust the request library to add
        # the Content-Type = multipart/form-data :
        request_header = self.cookie()

        logger.debug(
            "Importing Physical Objects Locators from file -> '%s'; calling -> %s",
            file_path,
            request_url,
        )

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> '%s' does not exist in path -> '%s'!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            files=settings_post_file,
            timeout=None,
            failure_message="Failed to import Physical Objects Locators from file -> '{}'".format(
                file_path
            ),
            parse_request_response=False,
        )

        if response and response.ok:
            return True

        return False

    # end method definition

    def import_security_clearance_codes(
        self, file_path: str, include_users: bool = False
    ) -> bool:
        """Import Security Clearance codes from a config file that is uploaded from the python pod

        Args:
            file_path (str): path + filename of config file in Python container filesystem
            include_users (bool): defines if users should be included or not
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["securityClearancesUrl"] + "/importCodes"

        # When we upload files using the 'files' parameter, the request must be encoded
        # as multipart/form-data, which allows binary data (like files) to be sent along
        # with other form data.
        # The requests library sets this header correctly if the 'files' parameter is provided.
        # So we just put the cookie in the header and trust the request library to add
        # the Content-Type = multipart/form-data :
        request_header = self.cookie()

        logger.debug(
            "Importing Security Clearance Codes from file -> '%s'; calling -> %s",
            file_path,
            request_url,
        )

        settings_post_data = {"includeusers": include_users}

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> '%s' does not exist in path -> '%s'!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=settings_post_data,
            files=settings_post_file,
            timeout=None,
            failure_message="Failed to import Security Clearance Codes from file -> '{}'".format(
                file_path
            ),
            parse_request_response=False,
        )

        if response and response.ok:
            return True

        return False

    # end method definition

    def assign_user_security_clearance(
        self, user_id: int, security_clearance: int
    ) -> dict | None:
        """Assign a Security Clearance level to an Extended ECM user

        Args:
            user_id (int): ID of the user
            security_clearance (int): security clearance level to be set
        Returns:
            dict: REST response or None if the REST call fails.
        """

        assign_user_security_clearance_post_data = {
            "securityLevel": security_clearance,
        }

        request_url = self.config()[
            "userSecurityUrl"
        ] + "/{}/securityclearancelevel".format(user_id)
        request_header = self.request_form_header()

        logger.debug(
            "Assign security clearance -> %s to user with ID -> %s; calling -> %s",
            str(security_clearance),
            str(user_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=assign_user_security_clearance_post_data,
            timeout=None,
            failure_message="Failed to assign security clearance -> {} to user with ID -> {}".format(
                security_clearance, user_id
            ),
        )

    # end method definition

    def assign_user_supplemental_markings(
        self, user_id: int, supplemental_markings: list
    ) -> dict | None:
        """Assign a list of Supplemental Markings to a user

        Args:
            user_id (int): ID of the user
            supplemental_markings (list of strings): list of Supplemental Markings to be set
        Returns:
            dict: REST response or None if the REST call fails.
        """

        assign_user_supplemental_markings_post_data = {
            "suppMarks": supplemental_markings,
        }

        request_url = self.config()[
            "userSecurityUrl"
        ] + "/{}/supplementalmarkings".format(user_id)
        request_header = self.request_form_header()

        logger.debug(
            "Assign supplemental markings -> %s to user with ID -> %s; calling -> %s",
            str(supplemental_markings),
            str(user_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=assign_user_supplemental_markings_post_data,
            timeout=None,
            failure_message="Failed to assign supplemental markings -> {} to user with ID -> {}".format(
                supplemental_markings, user_id
            ),
        )

    # end method definition

    def get_workflow_definition(self, workflow_id: int) -> dict | None:
        """Get the workflow definition.

        Args:
            workflow_id (int): node ID of the workflow item (map)

        Returns:
            dict | None: workflow definition data

            Example:
            {
                'links': {
                    'data': {...}
                },
                'results': {
                    'definition': {
                        'data_packages': [
                            {
                                'data': {},
                                'description': None,
                                'sub_type': 2,
                                'type': 1
                            },
                            {
                                'data': {
                                    'data': {
                                        'data': {
                                            '25397_10': None,
                                            '25397_11': False,
                                            '25397_8': None,
                                            '25397_9': None
                                        },
                                        'definitions': {
                                            '25397': {...},
                                            '25397_10': {
                                                'allow_undefined': False,
                                                'bulk_shared': False,
                                                'default_value': None,
                                                'description': None,
                                                'hidden': False,
                                                'include_time': False,
                                                'key': '25397_10',
                                                'key_value_pairs': False,
                                                'multi_value': False,
                                                'multi_value_length_default': 1,
                                                'multi_value_length_fixed': True,
                                                'multi_value_length_max': 1,
                                                'multi_value_max_length': None,
                                                'multi_value_min_length': None,
                                                'multi_value_unique': False,
                                                'name': 'Approval Date',
                                                'persona': '',
                                                'read_only': False,
                                                'required': False,
                                                'type': -7,
                                                'type_llattribute': -7,
                                                'type_name': 'Date',
                                                'valid_values': [],
                                                'valid_values_name': []
                                            },
                                            '25397_11': {...},
                                            '25397_8': {...},
                                            '25397_9': {...}
                                        },
                                        'definitions_map': {
                                            '25397': [...]
                                        },
                                        'definitions_order': ['25397']
                                    },
                                    'definitions': {...},
                                    'definitions_map': {...},
                                    'definitions_order': [...]
                                },
                                'description': 'Please fill in all required attributes.',
                                'sub_type': 3,
                                'type': 1
                            },
                            {...},
                            {...}
                        ],
                        'tasks': [
                            {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}
                        ],
                        'workflow_id': 25397,
                        'workflow_roles': []
                    }
                }
            }
        """

        request_url = (
            self.config()["workflowUrl"] + "/" + str(workflow_id) + "/definition"
        )
        request_header = self.request_form_header()

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get definition of workflow with ID -> {}".format(
                workflow_id
            ),
        )

    # end method definition

    def get_workflow_attributes(
        self, workflow_id: int, form_prefix: str = "WorkflowForm"
    ) -> dict | None:
        """Get workflow attribute definition. It returns a dictionary
           to allow looking up attribute IDs based on the attribute names.

        Args:
            workflow_id (int): Node ID of the workflow.

        Returns:
            dict | None: Keys are the attribute names. Values are the attribute IDs.
                         None in case an error occurs.

            Example:
            {
                'Approval Date': {
                    'id': '25397_10',
                    'type': 'Date'
                    'form_id': 'WorkflowForm_10'
                },
                'Official': {
                    'id': '25397_11',
                    'type': 'Boolean'
                    'form_id': 'WorkflowForm_11'
                },
                'Approver': {
                    'id': '25397_8',
                    'type': 'Integer'
                    'form_id': 'WorkflowForm_8'
                },
                'Status': {
                    'id': '25397_9',
                    'type': 'String'
                    'form_id': 'WorkflowForm_9'
                }
            }
        """

        response = self.get_workflow_definition(workflow_id=workflow_id)

        if not response or not "results" in response:
            return None

        results = response["results"]
        if not "definition" in results:
            logger.error("Workflow definition is missing 'results' data structure!")
            return None

        # we just need the definition part of the workflow definition:
        definition = results["definition"]

        # in particular we want to lookup a specific data package
        # that includes the attribute definitions:
        if not "data_packages" in definition:
            logger.error("Workflow definition does not have data packages!")
            return None

        # Initialize the result dictionary:
        result = {}

        for data_package in definition["data_packages"]:
            data = data_package.get("data", None)
            if data and "definitions" in data:
                # We found the right data package with the attribute definitions!
                attribute_definitions = data["definitions"]
                for key, value in attribute_definitions.items():
                    attribute_type = value.get("type_name", None)
                    # the assoc represents the whole data structure
                    # and is not a single attribute - we skip it:
                    if attribute_type == "Assoc":
                        continue
                    # We construct the dict in a way that allows
                    # to lookup attribute IDs based on attribute names.
                    # we also add a key with the 'form_prefix' as the
                    # draft process needs it in that syntax.
                    form_id = form_prefix + "_" + key.split("_")[1]
                    result[value.get("name")] = {
                        "id": key,
                        "type": attribute_type,
                        "form_id": form_id,
                    }

        return result

    # end method definition

    def get_document_workflows(self, node_id: int, parent_id: int) -> list:
        """Get a list of available workflows for a document ID and a parent ID.

        Args:
            node_id (int): node ID of the document
            parent_id (int): node ID of the parent

        Returns:
            list: list of available workflows

            Example:
            {
                'links': {
                    'data': {...}
                },
                'results': {
                    'data': [
                        {
                            'DataID': 25397,
                            'Name': 'Contract Approval Workflow',
                            'WorkflowType': 100
                        },
                        {
                            'DataID': 25442,
                            'Name': 'Contract Approval Workflow (2 steps)',
                            'WorkflowType': 100
                        },
                        ...
                    ],
                    'fError': '',
                    'fErrorDetail': '',
                    'statusMsg': None}
                }
            }
        """

        request_url = self.config()[
            "docWorkflowUrl"
        ] + "?doc_id={}&parent_id={}".format(node_id, parent_id)
        request_header = self.request_form_header()

        logger.debug(
            "Get workflows for node ID -> %s and parent ID -> %s; calling -> %s",
            str(node_id),
            str(parent_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get workflows for node ID -> {} and parent ID -> {}".format(
                node_id, parent_id
            ),
        )

    # end method definition

    def get_workflows_by_kind_and_status(
        self,
        kind: str | None = None,
        status: str | list | None = None,
        sort: str | None = None,
    ) -> list:
        """Get a list of workflows with a defined kind and status. This method is personlalized, you
           need to call it with the user thse workflows are related to

        Args:
            kind (str | None, optional): "Managed", "Initiated", "Both". Defaults to None.
            status (str | None, optional): "ontime", "workflowlate", "stopped", "completed". Defaults to None (=all).
            sort (str | None, optional): Sorting order, like "name asc", "name desc", "data_initiated asc", "status_key desc".
                                         Defaults to None.

        Returns:
            list: list of matching workflows

            Example:
            {
                "links": {
                    "data": {
                        "self": {
                            "body": "",
                            "content_type": "",
                            "href": "/api/v2/workflows/status",
                            "method": "GET",
                            "name": ""
                        }
                    }
                },
                "results": [
                    {
                        "data": {
                            "wfstatus": {
                                "assignee": [
                                    {
                                        "userId": 15665,
                                        "loginName": "dfoxhoven",
                                        "firstName": "Deke",
                                        "lastName": "Foxhoven",
                                        "emailAddress": "dfoxhoven@dev.idea-te.eimdemo.com",
                                        "phone": ""
                                    }
                                ],
                                "assignee_count": 1,
                                "comments_on": true,
                                "current_assignee": "Deke Foxhoven",
                                "date_initiated": "2024-09-27T15:50:47",
                                "due_date": "",
                                "parallel_steps": [
                                    {
                                        "process_id": 160580,
                                        "subprocess_id": 160580,
                                        "task_id": 1,
                                        "task_name": "Approver",
                                        "task_due_date": "",
                                        "task_start_date": "2024-09-27T15:51:13",
                                        "task_status": "ontime",
                                        "task_assignees": {
                                            "assignee": [
                                                {
                                                    "userId": 15665,
                                                    "loginName": "dfoxhoven",
                                                    "firstName": "Deke",
                                                    "lastName": "Foxhoven",
                                                    "emailAddress": "dfoxhoven@dev.idea-te.eimdemo.com",
                                                    "phone": ""
                                                }
                                            ],
                                            "assigneeCount": 1,
                                            "currentAssignee": "Deke Foxhoven"
                                        }
                                    }
                                ],
                                "process_id": 160580,
                                "status_key": "ontime",
                                "step_name": "Approver",
                                "steps_count": 1,
                                "subprocess_id": 160580,
                                "task_id": 1,
                                "wf_name": "Contract Approval Workflow (1 step)"
                            }
                        },
                        "definitions": {
                            "wfstatus": {
                                "assignee": {
                                    "allow_undefined": false,
                                    "bulk_shared": false,
                                    "default_value": null,
                                    "description": null,
                                    "hidden": false,
                                    "key": "assignee",
                                    "max_value": null,
                                    "min_value": null,
                                    "multi_value": false,
                                    "name": "Assigned to",
                                    "persona": "",
                                    "read_only": true,
                                    "required": false,
                                    "type": 2,
                                    "type_name": "Integer",
                                    "valid_values": [],
                                    "valid_values_name": []
                                },
                                "date_initiated": {
                                    "allow_undefined": false,
                                    "bulk_shared": false,
                                    "default_value": null,
                                    "description": null,
                                    "hidden": false,
                                    "include_time": true,
                                    "key": "date_initiated",
                                    "multi_value": false,
                                    "name": "Start Date",
                                    "persona": "",
                                    "read_only": true,
                                    "required": false,
                                    "type": -7,
                                    "type_name": "Date",
                                    "valid_values": [],
                                    "valid_values_name": []
                                },
                                "due_date": {
                                    "allow_undefined": false,
                                    "bulk_shared": false,
                                    "default_value": null,
                                    "description": null,
                                    "hidden": false,
                                    "include_time": true,
                                    "key": "due_date",
                                    "multi_value": false,
                                    "name": "Step Due Date",
                                    "persona": "",
                                    "read_only": true,
                                    "required": false,
                                    "type": -7,
                                    "type_name": "Date",
                                    "valid_values": [],
                                    "valid_values_name": []
                                },
                                "status_key": {
                                    "allow_undefined": false,
                                    "bulk_shared": false,
                                    "default_value": null,
                                    "description": null,
                                    "hidden": false,
                                    "key": "status_key",
                                    "max_length": null,
                                    "min_length": null,
                                    "multi_value": false,
                                    "multiline": false,
                                    "multilingual": false,
                                    "name": "Status",
                                    "password": false,
                                    "persona": "",
                                    "read_only": true,
                                    "regex": "",
                                    "required": false,
                                    "type": -1,
                                    "type_name": "String",
                                    "valid_values": [],
                                    "valid_values_name": []
                                },
                                "step_name": {
                                    "allow_undefined": false,
                                    "bulk_shared": false,
                                    "default_value": null,
                                    "description": null,
                                    "hidden": false,
                                    "key": "step_name",
                                    "max_length": null,
                                    "min_length": null,
                                    "multi_value": false,
                                    "multiline": false,
                                    "multilingual": true,
                                    "name": "Current Step",
                                    "password": false,
                                    "persona": "",
                                    "read_only": true,
                                    "regex": "",
                                    "required": false,
                                    "type": -1,
                                    "type_name": "String",
                                    "valid_values": [],
                                    "valid_values_name": []
                                },
                                "wf_name": {
                                    "allow_undefined": false,
                                    "bulk_shared": false,
                                    "default_value": null,
                                    "description": null,
                                    "hidden": false,
                                    "key": "wf_name",
                                    "max_length": null,
                                    "min_length": null,
                                    "multi_value": false,
                                    "multiline": false,
                                    "multilingual": true,
                                    "name": "Workflow",
                                    "password": false,
                                    "persona": "",
                                    "read_only": true,
                                    "regex": "",
                                    "required": false,
                                    "type": -1,
                                    "type_name": "String",
                                    "valid_values": [],
                                    "valid_values_name": []
                                }
                            }
                        },
                        "definitions_map": {
                            "wfstatus": {}
                        },
                        "definitions_order": {
                            "wfstatus": [
                                "status_key",
                                "due_date",
                                "wf_name",
                                "step_name",
                                "assignee",
                                "date_initiated"
                            ]
                        },
                        "permissions": {
                            "Archive": true,
                            "ChangeAttr": true,
                            "ChangeRoute": true,
                            "Delete": true,
                            "ManagerPerms": true,
                            "SeeDetail": true,
                            "Stop": true,
                            "Suspend": true
                        }
                    }
                ]
            }
        """

        query = {}
        if kind:
            query["kind"] = kind
        if status:
            query["wstatus"] = status
        if sort:
            query["sort"] = sort
        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = self.config()["workflowUrl"] + "/status?{}".format(encoded_query)
        request_header = self.request_form_header()

        logger.debug(
            "Get workflows of kind -> '%s' and status -> '%s'; calling -> %s",
            kind,
            str(status),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get workflows of kind -> {} and status -> {}".format(
                kind, str(status)
            ),
        )

    # end method definition

    def get_workflow_status(self, process_id: int) -> dict | None:
        """Get the status (task list) of a workflow instance (process)

        Args:
            process_id (int): ID of the process (worflow instance)

        Returns:
            dict | None: Task list of the workflow instance or None if the request fails.

            Example result:
            {
                'links': {
                    'data': {
                        'self': {
                            'body': '',
                            'content_type': '',
                            'href': '/api/v2/workflows/status/processes/159324',
                            'method': 'GET',
                            'name': ''
                        }
                    }
                },
                'results': {
                    'attachments': {'attachment_folder_id': 159311},
                    'data_packages': [
                        {
                            'TYPE': 1,
                            'SUBTYPE': 1,
                            'USERDATA': 159311,
                            'DESCRIPTION': ''
                        },
                        {
                            'TYPE': 1,
                            'SUBTYPE': 2,
                            'USERDATA': 159314,
                            'DESCRIPTION': ''
                        },
                        {
                            'TYPE': 1,
                            'SUBTYPE': 3,
                            'USERDATA': {...},
                            'DESCRIPTION': 'Please fill in all required attributes.'
                        }
                    ],
                    'permissions': {
                        'Archive': True,
                        'ChangeAttr': True,
                        'ChangeRoute': True,
                        'Delete': True,
                        'ManagerPerms': True,
                        'SeeDetail': True,
                        'Stop': True,
                        'Suspend': True
                    },
                    'step_list': {
                        'completed': [],
                        'current': [
                            {
                                'process_id': 159314,
                                'subprocess_id': 159314,
                                'task_id': 10,
                                'task_name': 'set Item Status = pending approval',
                                'task_due_date': '',
                                'task_start_date': '2024-10-03T15:21:23',
                                'task_status': 'ontime',
                                'task_assignees': {
                                    'assignee': [
                                        {
                                            'userId': 1000,
                                            'loginName': 'Admin',
                                            'firstName': '',
                                            'lastName': '',
                                            'emailAddress': '',
                                            'phone': ''
                                        }
                                    ],
                                    'assigneeCount': 1,
                                    'currentAssignee': ' '
                                }
                            }
                        ],
                        'next': []
                    },
                    'wf_details': {
                        'date_initiated': '2024-10-03T15:21:23',
                        'due_date': '',
                        'initiator': {
                            'firstName': 'Paul',
                            'lastName': 'Williams',
                            'loginName': 'pwilliams',
                            'userId': 15235
                        },
                        'status': 'ontime',
                        'wf_name': 'Test without due date',
                        'work_workID': 159314
                    }
                }
            }
        """

        request_url = self.config()["workflowUrl"] + "/status/processes/{}".format(
            process_id
        )
        request_header = self.request_form_header()

        logger.debug(
            "Get workflow status (task list) of process ID -> %s; calling -> %s",
            str(process_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get workflow status for process ID -> {}".format(
                process_id
            ),
        )

    # end method definition

    def create_draft_process(self, workflow_id, documents: list) -> dict | None:
        """Initiate a draft process. This is the first step to start a process (workflow instance)

        Args:
            workflow_id (int): Node ID of the workflow maps
            documents (list): node IDs of the attachmewnt documents

        Returns:
            dict | None: Task list of the workflow instance or None if the request fails.

            Example:
            {
                'links': {
                    'data': {...}
                },
                'results': {
                    'draftprocess_id': 157555,
                    'workflow_type': '1_1'}
                }
            }
        """

        draft_process_body_post_data = {
            "workflow_id": workflow_id,
            "doc_ids": documents,
            #            "AttachDocuments": True, # THIS DOES NOT WORK!!!
        }

        request_url = self.config()["draftProcessUrl"]
        request_header = self.request_form_header()

        logger.debug(
            "Create a draft process for workflow with ID -> %s and body -> %s; calling -> %s",
            str(workflow_id),
            str(draft_process_body_post_data),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data={"body": json.dumps(draft_process_body_post_data)},
            timeout=None,
            failure_message="Failed to create draft process from workflow with ID -> {}".format(
                workflow_id
            ),
        )

    # end method definition

    def get_draft_process(self, draftprocess_id: int) -> dict | None:
        """Get draft process data.

        Args:
            draftprocess_id (int): ID of an existing draft process

        Returns:
            dict | None: Get the details for a draft process.
                         Delivers None in case of an error.

            Example result:
            {
                'data': {
                    'actions': [
                        {
                            'key': 'Initiate',
                            'label': 'Start'
                        }
                    ],
                    'attachment_centric_default_mode': 'properties',
                    'attachments_on': True,
                    'authentication': False,
                    'comments_on': True,
                    'data_packages': [...],
                    'enableTopAlignedLabel': True,
                    'instructions': 'Please pick the Approver (type-ahead search)\n\n',
                    'process_id': 158037,
                    'task': {...},
                    'title': 'Contract Approval Workflow (1 step)',
                    'workflow_type': '1_1'
                },
                'forms': [
                    {...}
                ]
            }
        """

        request_url = (
            self.config()["draftProcessFormUrl"]
            + "/update"
            + "?draftprocess_id="
            + str(draftprocess_id)
        )
        request_header = self.request_form_header()

        logger.debug(
            "Get draft process with ID -> %s; calling -> %s",
            str(draftprocess_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get draft process with ID -> {}".format(
                draftprocess_id
            ),
        )

    # end method definition

    def update_draft_process(
        self,
        draftprocess_id: int,
        title: str = "",
        due_date: str = "",
        values: dict | None = None,
    ) -> dict | None:
        """Update a draft process with values. These can either be given via dedicated parameters
           like title and due_date or with a generic value dictionary.

        Args:
            draftprocess_id (int): ID of the draft process that has been created before with create_draft_process()
            title (str): Title of the process
            due_date (str, optional): due date for the process. Defaults to "".
            values (dict | None, optional): values for workflow attributes. Defaults to None.

        Returns:
            dict | None: Respinse of the REST API or None in case of an error.
        """

        request_url = self.config()["draftProcessUrl"] + "/" + str(draftprocess_id)
        request_header = self.request_form_header()

        logger.debug(
            "Update draft process with ID -> %s with these values -> %s; calling -> %s",
            str(draftprocess_id),
            str(values),
            request_url,
        )

        if not values:
            values = {}

        if title:
            values["WorkflowForm_Title"] = title
        if due_date:
            values["WorkflowForm_WorkflowDueDate"] = due_date

        update_draft_process_body_put_data = {
            "action": "formUpdate",
            "values": values,
        }

        # this call needs a "body" tag around the
        # actual payload - otherwise it will return just "None"
        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data={"body": json.dumps(update_draft_process_body_put_data)},
            timeout=None,
            failure_message="Failed to update draft process with ID -> {} with these values -> {}".format(
                draftprocess_id, values
            ),
        )

    # end method definition

    def initiate_draft_process(
        self,
        draftprocess_id: int,
        comment: str = "",
    ) -> dict | None:
        """Initiate a process (workflow instance) from a draft process.

        Args:
            draftprocess_id (int): ID of the draft process that has been created before with create_draft_process()
            title (str): Title of the process
            comment (str, optional): comment of the process. Defaults to "".
            due_date (str, optional): due date for the process. Defaults to "".
            values (dict | None, optional): values for workflow attributes. Defaults to None.

        Returns:
            dict | None: Respinse of the REST API or None in case of an error.

            Example:
            {
                'links': {
                    'data': {
                        'self': {
                            'body': '',
                            'content_type': '',
                            'href': '/api/v2/draftprocesses/158037',
                            'method': 'PUT',
                            'name': ''
                        }
                    }
                },
                'results': {
                    'custom_message': 'Contract Approval Workflow was initiated successfully.',
                    'process_id': 165496,
                    'WorkID': None,
                    'WRID': None
                }
            }
        """

        request_url = self.config()["draftProcessUrl"] + "/" + str(draftprocess_id)
        request_header = self.request_form_header()

        logger.debug(
            "Initiate a process (workflow instance) from a draft process with ID -> %s; calling -> %s",
            str(draftprocess_id),
            request_url,
        )

        initiate_process_body_put_data = {
            "action": "Initiate",
            "comment": comment,
        }

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data={"body": json.dumps(initiate_process_body_put_data)},
            timeout=None,
            failure_message="Failed to initiate draft process with ID -> {}".format(
                draftprocess_id
            ),
        )

    # end method definition

    def get_process_task(
        self, process_id: int, subprocess_id: int | None = None, task_id: int = 1
    ) -> dict | None:
        """Get the task information of a workflow assignment.
           This method must be called with the user authenticated
           that has the task in ts inbox.

        Args:
            process_id (int): process ID of the workflow instance
            subprocess_id (int | None, optional): Subprocess ID. Defaults to None (= process_id).
            task_id (int, optional): Task ID. Defaults to 1.

        Returns:
            dict | None: Response of REST API call. None in case an error occured.

            Example:
            {
                'data': {
                    'actions': [
                        {
                            'key': 'Delegate',
                            'label': 'Forward'
                        }
                    ],
                    'attachments_on': True,
                    'authentication': False,
                    'comments_on': True,
                    'custom_actions': [
                        {
                            'key': 'Approve',
                            'label': 'Approve'
                        },
                        {
                            'key': 'Reject',
                            'label': 'Reject'
                        }
                    ],
                    'data_packages': [
                        {
                            'data': {
                                'attachment_folder_id': 115292
                            },
                            'sub_type': 1,
                            'type': 1
                        }
                    ],
                    'instructions': 'Paul Williams has sent this contract to you for review. \n\n1. Read the attached document in-depth\n2. Enter the approval date\n3. Then click the Approve or Reject button\n4. Enter a Comment if prompted',
                    'message': None,
                    'process_id': 115295,
                    'subprocess_id': 115295,
                    'task': {...},
                    'task_id': 1,
                    'title': 'Approver'
                },
                'forms': [
                    {...}
                ]
            }
        """

        if subprocess_id is None:
            subprocess_id = process_id

        request_url = (
            self.config()["processTaskUrl"]
            + "?process_id="
            + str(process_id)
            + "&subprocess_id="
            + str(subprocess_id)
            + "&task_id="
            + str(task_id)
        )
        request_header = self.request_form_header()

        logger.debug(
            "Get a process (workflow instance) task for process with ID -> %s; calling -> %s",
            str(process_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=None,
            failure_message="Failed to get task for process with ID -> {}".format(
                process_id
            ),
        )

    # end method definition

    def update_process_task(
        self,
        process_id: int,
        subprocess_id: int | None = None,
        task_id: int = 1,
        values: dict | None = None,
        action: str = "formUpdate",
        custom_action: str = "",
        comment: str = "",
    ) -> dict | None:
        """Update a process with values in a task. This method needs to be called with the user
           that has the task in its inbox (My ToDo - Workflows). It can update the task data (formUpdate)
           and/or send on the task to the next workflow step (action or custom_action).

            TODO: this method is currently untested.

        Args:
            process_id (int): ID of the draft process that has been created before with create_draft_process()
            task_id (int, optional): ID of the task. Default is 1.
            values (dict | None, optional): values for workflow attributes. Defaults to None. It is only
                                            used if action = "formUpdate".
            action (str, optional): the name of the action to process. The default is "formUpdate".
            custom_action (str, optional): Here we can have custom actions like "Approve" or "Reject".
                                           if "custom_action" is not None then the "action" parameter is ignored.
            comment (str, optional): the comment given with the action

        Returns:
            dict | None: Respinse of the REST API or None in case of an error.
        """

        if not action and not custom_action:
            logger.error(
                "Either 'action' or 'custom_action' is required for updating a process task!"
            )
            return None

        if subprocess_id is None:
            subprocess_id = process_id

        request_url = (
            self.config()["processUrl"]
            + "/"
            + str(process_id)
            + "/subprocesses/"
            + str(subprocess_id)
            + "/tasks/"
            + str(task_id)
        )
        request_header = self.request_form_header()

        if values:
            logger.debug(
                "Update task with ID -> %s of process with ID -> %s with these values -> %s; calling -> %s",
                str(task_id),
                str(process_id),
                str(values),
                request_url,
            )

        if not values:
            values = {}

        if not custom_action:
            update_process_task_body_put_data = {
                "action": action,
            }
            if action == "formUpdate":
                update_process_task_body_put_data["values"] = values
            logger.debug(
                "Execute action -> '%s' for process with ID -> %s",
                action,
                str(process_id),
            )
        else:  # we have a custom action:
            update_process_task_body_put_data = {
                "custom_action": custom_action,
            }
            logger.debug(
                "Execute custom action -> '%s' for process with ID -> %s",
                custom_action,
                str(process_id),
            )
        if comment:
            update_process_task_body_put_data["comment"] = comment

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data={"body": json.dumps(update_process_task_body_put_data)},
            timeout=None,
            failure_message="Failed to update task with ID -> {} of process with ID -> {} with these values -> {}".format(
                task_id, process_id, values
            ),
        )

    # end method definition

    def check_workspace_aviator(
        self,
        workspace_id: int,
    ) -> bool:
        """Check if Content Aviator is enabled for a workspace

        Args:
            workspace_id (int): node ID of the workspace
        Returns:
            bool: True if aviator is enabled, False otherwise
        """

        response = self.get_node_actions(
            node_id=workspace_id, filter_actions=["disableai", "enableai"]
        )
        result_data = self.get_result_value(
            response=response,
            key=str(workspace_id),
        )
        if result_data and "data" in result_data:
            data = result_data["data"]
            if "disableai" in data:
                logger.debug(
                    "Aviator is enabled for workspace with ID -> %s", str(workspace_id)
                )
                return True
            elif "enableai" in data:
                logger.debug(
                    "Aviator is disabled for workspace with ID -> %s", str(workspace_id)
                )

        return False

    # end method definition

    def update_workspace_aviator(
        self,
        workspace_id: int,
        status: bool,
    ) -> dict | None:
        """Enable or disable the Content Aviator for a workspace

        Args:
            workspace_id (int): node ID of the workspace
            status (bool): True = enable, False = disable Content Aviator for this workspace
        Returns:
            dict: REST response or None if the REST call fails.
        """

        aviator_status_put_data = {
            "enabled": status,
        }

        request_url = self.config()["aiUrl"] + "/{}".format(workspace_id)
        request_header = self.request_form_header()

        if status is True:
            logger.debug(
                "Enable Content Aviator for workspace with ID -> %s; calling -> %s",
                str(workspace_id),
                request_url,
            )
        else:
            logger.debug(
                "Disable Content Aviator for workspace with ID -> %s; calling -> %s",
                str(workspace_id),
                request_url,
            )

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data=aviator_status_put_data,
            timeout=None,
            failure_message="Failed to change status for Content Aviator on workspace with ID -> {}".format(
                workspace_id
            ),
        )

    # end method definition

    def volume_translator(
        self,
        current_node_id: int,
        translator: object,
        languages: list,
        simulate: bool = False,
    ):
        """Experimental code to translate the item names and item descriptions in a given hierarchy.
           The actual translation is done by a tranlator object. This recursive method just
           traverses the hierarchy and calls the translate() method of the translator object.

        Args:
            current_node_id (int): current node ID to translate
            translator (object): this object needs to be created based on the "Translator" class
                                 and passed to this method
            languages (list): list of target languages
            simulate (bool, optional): if True, do not really rename but just traverse and log info.
                                       the default is False
        """
        # Get current node based on the ID:
        current_node = self.get_node(current_node_id)
        current_node_id = self.get_result_value(current_node, "id")

        name = self.get_result_value(current_node, "name")
        description = self.get_result_value(current_node, "description")
        names_multilingual = self.get_result_value(current_node, "name_multilingual")
        descriptions_multilingual = self.get_result_value(
            current_node, "description_multilingual"
        )

        for language in languages:
            if language == "en":
                continue
            # Does the language not exist as metadata language or is it already translated?
            # Then we skip this language:
            if (
                language in names_multilingual
                and names_multilingual["en"]
                and not names_multilingual[language]
            ):
                names_multilingual[language] = translator.translate(
                    "en", language, names_multilingual["en"]
                )
                logger.debug(
                    "Translate name of node -> %s from -> '%s' (%s) to -> '%s' (%s)",
                    current_node_id,
                    name,
                    "en",
                    names_multilingual[language],
                    language,
                )
            if (
                language in descriptions_multilingual
                and descriptions_multilingual["en"]
                and not descriptions_multilingual[language]
            ):
                descriptions_multilingual[language] = translator.translate(
                    "en", language, descriptions_multilingual["en"]
                )
                logger.debug(
                    "Translate description of node -> %s from -> '%s' (%s) to -> '%s' (%s)",
                    current_node_id,
                    name,
                    "en",
                    names_multilingual[language],
                    language,
                )

        # Rename node multi-lingual:
        if not simulate:
            self.rename_node(
                current_node_id,
                name,
                description,
                names_multilingual,
                descriptions_multilingual,
            )

        # Get children nodes of the current node:
        results = self.get_subnodes(current_node_id, limit=200)["results"]

        # Recursive call of all subnodes:
        for result in results:
            self.volume_translator(
                result["data"]["properties"]["id"], translator, languages
            )

    # end method definition

    def download_document_multi_threading(self, node_id: int, file_path: str):
        """Multi-threading variant of download_document()

        Args:
            node_id (int): Node ID of the document to download
            file_path (str): file system path - location to download to
        """

        # Aquire and Release Thread limit to limit parallel executions

        with self._semaphore:
            self.download_document(node_id=node_id, file_path=file_path)

    # end method definition

    def apply_filter(
        self,
        node: dict,
        current_depth: int = 0,
        filter_depth: int | None = None,
        filter_subtypes: list | None = None,
        filter_category: str | None = None,
        filter_attributes: dict | list | None = None,
    ) -> bool:
        """Check all defined filters for the given node.

        Args:
            node (dict): Current OTCS Node
            filter_depth (int | None, optional): Additive filter criterium for path depth. Defaults to None = filter not active.
            filter_subtype (list | None, optional): Additive filter criterium for workspace type. Defaults to None = filter not active.
            filter_category (str | None, optional): Additive filter criterium for workspace category. Defaults to None = filter not active.
            filter_attributes (dict | list | None, optional): _description_. Defaults to None.

        Returns:
            bool: Only for nodes that comply with ALL provided filters True is returned. Otherwise False.
        """

        if not node or not "type" in node or not "id" in node:
            logger.error("Illegal node!")
            return False

        if filter_subtypes and not node["type"] in filter_subtypes:
            logger.info(
                "Node type -> '%s' is not in filter node types -> %s. Node -> '%s' failed filter test.",
                node["type"],
                filter_subtypes,
                node["name"],
            )
            return False

        if filter_depth is not None and filter_depth != current_depth:
            logger.info(
                "Node is in depth -> %s which is different from filter depth -> %s. Node -> '%s' failed filter test.",
                current_depth,
                filter_depth,
                node["name"],
            )
            return False

        if filter_category:
            category_names = self.get_node_category_names(node_id=node["id"])
            if not category_names or filter_category not in category_names:
                logger.info(
                    "Node categories -> %s do not include filter category -> '%s'. Node -> '%s' failed filter test.",
                    category_names,
                    filter_category,
                    node["name"],
                )
                return False
            if filter_attributes:
                if isinstance(filter_attributes, dict):
                    filter_attributes = [filter_attributes]
                for filter_attribute in filter_attributes:
                    filter_category_name = filter_attribute.get(
                        "category", filter_category
                    )
                    if not filter_category_name:
                        logger.error(
                            "Attribute filter -> %s is missing category name!",
                            str(filter_attribute),
                        )
                        continue
                    filter_set_name = filter_attribute.get("set", None)
                    filter_attribute_name = filter_attribute.get("attribute", None)
                    if not filter_attribute_name:
                        logger.error(
                            "Attribute filter -> %s is missing attribute name!",
                            str(filter_attribute),
                        )
                        continue
                    filter_row = filter_attribute.get("row", None)
                    filter_value = filter_attribute.get("value", None)
                    actual_value = self.get_category_value_by_name(
                        node_id=node["id"],
                        category_name=filter_category_name,
                        set_name=filter_set_name,
                        attribute_name=filter_attribute_name,
                        set_row=filter_row,
                    )
                    # Both actual value and filter value can be strings or list of strings.
                    # So we need to handle a couple of cases here:

                    # Case 1: Data source delivers a list and filter value is a scalar value (int, str, float)
                    if isinstance(actual_value, list) and isinstance(
                        filter_value, (str, int, float)
                    ):
                        if filter_value not in actual_value:
                            return False
                    # Case 2: Data source delivers a scalar value and filter value is a list
                    elif isinstance(actual_value, (str, int, float)) and isinstance(
                        filter_value, list
                    ):
                        if actual_value not in filter_value:
                            return False
                    # Case 3: Both, filter and actual value are lists:
                    elif isinstance(actual_value, list) and isinstance(
                        filter_value, list
                    ):
                        # check if there's an non-empty intersetion set of both lists:
                        if not set(actual_value) & set(filter_value):
                            return False
                    elif isinstance(actual_value, (str, int, float)) and isinstance(
                        filter_value, (str, int, float)
                    ):
                        if actual_value != filter_value:
                            return False
                    else:
                        return False

        return True

    # end method definition

    def load_items(
        self,
        node_id: int,
        folder_path: list | None = None,
        current_depth: int = 0,
        workspace_type: int | None = None,
        workspace_id: int | None = None,
        workspace_name: str | None = None,
        workspace_description: str | None = None,
        filter_workspace_depth: int | None = None,
        filter_workspace_subtypes: list | None = None,
        filter_workspace_category: str | None = None,
        filter_workspace_attributes: dict | list | None = None,
        filter_item_depth: int | None = None,
        filter_item_category: str | None = None,
        filter_item_attributes: dict | list | None = None,
        workspace_metadata: bool = True,
        item_metadata: bool = True,
        skip_existing_downloads: bool = True,
    ) -> bool:
        """Create a Pandas Data Frame by traversing a given Content Server hierarchy and collecting workspace and document items.

        Args:
            node_id (int): currrent Node ID (in recursive processing). Initially this is the starting node (root of the traversal)
            folder_path (str, optional): The current path from the starting node to the current node. Defaults to None.
            current_depth (int): The current depth in the tree that is traversed.
            workspace_type (int | None, optional): Type of the workspace (if already found in the hierarchy). Defaults to None.
            workspace_id (int | None, optional): ID of the workspace (if already found in the hierarchy). Defaults to None.
            workspace_name (str | None, optional): Name of the workspace (if already found in the hierarchy). Defaults to None.
            workspace_description (str | None, optional): Description of the workspace (if already found in the hierarchy). Defaults to None.
            filter_workspace_depth (int | None, optional): Additive filter criterium for workspace path depth. Defaults to None = filter not active.
            filter_workspace_subtype (list | None, optional): Additive filter criterium for workspace type. Defaults to None = filter not active.
            filter_workspace_category (str | None, optional): Additive filter criterium for workspace category. Defaults to None = filter not active.
            filter_workspace_attributes (dict | list, optional): Additive filter criterium for workspace attribute values. Defaults to None = filter not active
            filter_item_depth (int | None, optional): Additive filter criterium for item path depth. Defaults to None = filter not active.
            filter_item_category (str | None, optional): Additive filter criterium for item category. Defaults to None = filter not active.
            filter_item_attributes (dict | list, optional): Additive filter criterium for item attribute values. Defaults to None = filter not active
        Returns:
            bool: True = success, False = Error
        """

        if folder_path is None:
            folder_path = []  # required for list concatenation below

        # Create folder if it does not exist
        try:
            os.makedirs(self._download_dir)
        except FileExistsError:
            pass

        # Aquire and Release threading semaphore to limit parallel executions
        # to not overload the source Content Server system:
        with self._semaphore:
            subnodes = self.get_subnodes(parent_node_id=node_id)

        if subnodes is None:
            subnodes = {"results": []}

        # Initialize traversal threads:
        traversal_threads = []

        for subnode in subnodes.get("results", []):
            subnode = subnode.get("data").get("properties")

            # Initiaze download threads for this subnode:
            download_threads = []

            match subnode["type"]:

                case 0 | 848:  # folder or workspace
                    # First we check if we have found a workspace already:
                    if not workspace_id:
                        # Second we apply the defined filters to the current node. Only "workspaces"
                        # that comply with ALL provided filters are considered and written into the data frame
                        found_workspace = self.apply_filter(
                            node=subnode,
                            current_depth=current_depth,
                            filter_depth=filter_workspace_depth,
                            filter_subtypes=filter_workspace_subtypes,
                            filter_category=filter_workspace_category,
                            filter_attributes=filter_workspace_attributes,
                        )
                    else:
                        logger.info(
                            "Found folder or workspace -> '%s' (%s) inside workspace with ID -> %s. So this container cannot be a workspace.",
                            subnode["name"],
                            subnode["id"],
                            workspace_id,
                        )
                        # otherwise the current node cannot be a workspace as we are already in a workspace!
                        # For future improvements we could look at supporting sub-workspaces:
                        found_workspace = False

                    if found_workspace:
                        logger.info(
                            "Found workspace -> '%s' (%s) in depth -> %s. Adding to Data Frame...",
                            subnode["name"],
                            subnode["id"],
                            current_depth,
                        )
                        # DON'T change workspace_id here!
                        # This would break the for loop logic!

                        #
                        # Construct a dictionary 'row' that we will add
                        # to the resulting data frame:
                        #
                        row = {}
                        row["workspace_type"] = subnode["type"]
                        row["workspace_id"] = subnode["id"]
                        row["workspace_name"] = subnode["name"]
                        row["workspace_description"] = subnode["description"]
                        row["workspace_outer_path"] = folder_path
                        if workspace_metadata:
                            categories = self.get_node_categories(
                                subnode["id"], metadata=False
                            )
                            if categories and categories["results"]:
                                for category in categories["results"]:
                                    if (
                                        not "data" in category
                                        or not "categories" in category["data"]
                                    ):
                                        continue
                                    attributes = category["data"]["categories"]
                                    for key in attributes:
                                        value = attributes[key]
                                        row["workspace_" + key] = value

                        # Now we add the article to the Pandas Data Frame in the Data class:
                        with self._data.lock():
                            self._data.append(row)
                        subfolder = []  # now we switch to workspace inner path
                    # end if found_workspace:
                    else:  # we treat the current folder / workspace just as a container
                        logger.info(
                            "Node -> '%s' (%s) in depth -> %s is NOT a workspace. Keep traversing...",
                            subnode["name"],
                            subnode["id"],
                            current_depth,
                        )
                        subfolder = folder_path + [subnode["name"]]

                    # Recursive call to start threads for sub-items:
                    thread = threading.Thread(
                        target=self.load_items,
                        args=(
                            subnode["id"],
                            subfolder,
                            current_depth + 1,
                            (
                                workspace_type  # pass down initial parameter value if subnode is not the workspace
                                if not found_workspace
                                else subnode["type"]
                            ),
                            (
                                workspace_id  # pass down initial parameter value if subnode is not the workspace
                                if not found_workspace
                                else subnode["id"]
                            ),
                            (
                                workspace_name  # pass down initial parameter value if subnode is not the workspace
                                if not found_workspace
                                else subnode["name"]
                            ),
                            (
                                workspace_description  # pass down initial parameter value if subnode is not the workspace
                                if not found_workspace
                                else subnode["description"]
                            ),
                            filter_workspace_depth,
                            filter_workspace_subtypes,
                            filter_workspace_category,
                            filter_workspace_attributes,
                            filter_item_depth,
                            filter_item_category,
                            filter_item_attributes,
                            workspace_metadata,
                            item_metadata,
                            skip_existing_downloads,
                        ),
                        name="traverse_node_{}".format(subnode["id"]),
                    )
                    thread.start()
                    traversal_threads.append(thread)

                case 1:  # shortcuts
                    pass

                case 854:  # Related Workspaces - we don't want to run into loops!
                    pass

                case 751:  # E-Mail folders
                    pass

                case 123469:  # Forum
                    pass

                case 144:  # document
                    # We apply the defined filters to the current node. Only "documents"
                    # that comply with ALL provided filters are considered and written into the data frame
                    found_document = self.apply_filter(
                        node=subnode,
                        current_depth=current_depth,
                        filter_depth=filter_item_depth,
                        filter_category=filter_item_category,
                        filter_attributes=filter_item_attributes,
                    )

                    if not found_document:
                        continue

                    # We use the node ID as the filename to avoid any
                    # issues with too long or not valid file names.
                    # As the Pandas DataFrame has all information
                    # this is easy to resolve at upload time.
                    file_path = "{}/{}".format(self._download_dir, subnode["id"])

                    # We only consider documents that are inside the defined "workspaces":
                    if workspace_id:
                        logger.info(
                            "Found document -> '%s' (%s) in depth -> %s inside workspace -> '%s' (%s)",
                            subnode["name"],
                            subnode["id"],
                            current_depth,
                            workspace_name,
                            workspace_id,
                        )
                    else:
                        logger.warning(
                            "Found document -> '%s' (%s) in depth -> %s outside of workspace",
                            subnode["name"],
                            subnode["id"],
                            current_depth,
                        )

                    # We download only if not downloaded before or if downloaded
                    # before but forced to re-download:
                    if not os.path.exists(file_path) or not skip_existing_downloads:
                        #
                        # Start anasynchronous Download Thread:
                        #
                        logger.info(
                            "Downloading file -> %s...",
                            file_path,
                        )
                        thread = threading.Thread(
                            target=self.download_document_multi_threading,
                            args=(subnode["id"], file_path),
                            name="download_document_node_{}".format(subnode["id"]),
                        )
                        thread.start()
                        download_threads.append(thread)
                    else:
                        logger.info(
                            "File -> %s has been downloaded before. Skipping download...",
                            file_path,
                        )

                    #
                    # Construct a dictionary 'row' that we will add
                    # to the resulting data frame:
                    #
                    row = {}
                    # First we include some key workspace data to associate
                    # the itemwith the workspace:
                    row["workspace_type"] = workspace_type
                    row["workspace_id"] = workspace_id
                    row["workspace_name"] = workspace_name
                    row["workspace_description"] = workspace_description
                    row["item_id"] = str(subnode["id"])
                    row["item_name"] = subnode["name"]
                    row["item_description"] = subnode["description"]
                    row["item_path"] = folder_path
                    row["item_download_name"] = str(subnode["id"])
                    row["item_mime_type"] = subnode["mime_type"]
                    if item_metadata:
                        categories = self.get_node_categories(
                            subnode["id"], metadata=False
                        )
                        if categories and categories["results"]:
                            for category in categories["results"]:
                                if (
                                    not "data" in category
                                    or not "categories" in category["data"]
                                ):
                                    continue
                                attributes = category["data"]["categories"]
                                for key in attributes:
                                    value = attributes[key]
                                    row["item_" + key] = value

                    # Now we add the row to the Pandas Data Frame in the Data class:
                    logger.info(
                        "Adding document -> '%s' (%s) to data frame...",
                        row["item_name"],
                        row["item_id"],
                    )
                    with self._data.lock():
                        self._data.append(row)
                case 140:  # url
                    logger.info(
                        "Found URL object %s with %s", subnode["id"], subnode["url"]
                    )

                case _:
                    logger.warning(
                        "Don't know what to do with item -> %s (%s) of type %s",
                        subnode["name"],
                        subnode["id"],
                        subnode["type"],
                    )

            # Wait for all download threads to complete:
            for thread in download_threads:
                thread.join()

        # Wait for all traversal threads to complete:
        for thread in traversal_threads:
            thread.join()

        return True

    # end method definition

    def feme_embedd_metadata(
        self,
        node_id: int,
        node_type: int = 144,
        crawl: bool = False,
        wait_for_completion: bool = True,
        message_override: dict = {},
        timeout: float = 10.0,
    ):
        """RUN FEME metadata embedding on provided node for Aviator

        Args:
            node_id (int): Node ID
            node_type (int, optional): Subtype of the node. Defaults to 144.
            crawl (bool, optional): _description_. Defaults to False.
            wait_for_completion (bool, optional): _description_. Defaults to True.
            message_override (dict, optional): _description_. Defaults to {}.
            timout (float): Time in seconds to wait until the WebSocket times out. Defaults to 10.0
        """

        async def _inner(
            uri: str,
            node_id: int,
            node_type: int,
            crawl: bool,
            wait_for_completion: bool,
            message_override: dict,
            timeout: float,
        ):

            logger.debug("Open WebSocket connection to %s", uri)
            async with websockets.connect(uri) as websocket:

                # define it one node, or all childs should be processed
                task = ("crawl" if crawl else "index",)
                finished = "crawled" if crawl else "uploaded"

                message = {
                    "task": task,
                    "nodes": [{"id": node_id, "type": node_type}],
                    "documents": False,
                    "workspaces": True,
                    "images": False,
                    "binaries": False,
                    "upload": True,
                    "remove": False,
                    "imagePrompt": "Extract all information from the picture, please.",
                    "maxRelations": 0,
                }
                message.update(message_override)
                logger.debug("Sending message via WebSocket -> %s", message)
                await websocket.send(json.dumps(message))

                # Continuously listen for messages
                while wait_for_completion:
                    response = await asyncio.wait_for(
                        websocket.recv(), timeout=timeout
                    )  # await websocket.recv()  # Receive response

                    logger.debug("Received message via WebSocket -> %s", response)
                    response = json.loads(response)

                    if response.get("name", None) == finished:  # crawled
                        logger.info(
                            "Received completed message via WebSocket, close connection"
                        )
                        break

        event_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(event_loop)

        uri = self._config["feme_uri"]
        task = _inner(
            uri=uri,
            node_id=node_id,
            node_type=node_type,
            crawl=crawl,
            wait_for_completion=wait_for_completion,
            message_override=message_override,
            timeout=timeout,
        )

        try:
            event_loop.run_until_complete(task)
        except websockets.exceptions.ConnectionClosed as exc:  # :
            logger.error("WebSocket connection was closed: %s", exc)

        except TimeoutError:
            logger.error(
                "Error during Feme WebSocket connection: TimeoutError, WebSocket did not receive a message in time (%ss)",
                timeout,
            )

        except Exception as exc:
            logger.error("Error during Feme WebSocket connection: %s", exc)

        event_loop.close()

__init__(protocol, hostname, port, public_url=None, username=None, password=None, user_partition='Content Server Members', resource_name='cs', default_license='X3', otds_ticket=None, base_path='/cs/cs', thread_number=3, download_dir='/tmp/contentserver', feme_uri=None)

Initialize the OTCS object

Parameters:

Name Type Description Default
protocol str

Either http or https.

required
hostname str

The hostname of Extended ECM server to communicate with.

required
port int

The port number used to talk to the Extended ECM server.

required
public_url str

public (external) URL

None
username str

The admin user name of Extended ECM. Optional if otds_ticket is provided.

None
password str

The admin password of Extended ECM. Optional if otds_ticket is provided.

None
user_partition str

Name of the OTDS partition for OTCS users. Default is "Content Server Members".

'Content Server Members'
resource_name str

Name of the OTDS resource for OTCS. Dault is "cs".

'cs'
default_license str

name of the default user license. Default is "X3".

'X3'
otds_ticket str

Authentication ticket of OTDS

None
Source code in pyxecm/otcs.py
def __init__(
    self,
    protocol: str,
    hostname: str,
    port: int,
    public_url: str | None = None,
    username: str | None = None,
    password: str | None = None,
    user_partition: str = "Content Server Members",
    resource_name: str = "cs",
    default_license: str = "X3",
    otds_ticket: str | None = None,
    base_path: str = "/cs/cs",
    thread_number: int = 3,
    download_dir: str = "/tmp/contentserver",
    feme_uri: str | None = None,
):
    """Initialize the OTCS object

    Args:
        protocol (str): Either http or https.
        hostname (str): The hostname of Extended ECM server to communicate with.
        port (int): The port number used to talk to the Extended ECM server.
        public_url (str): public (external) URL
        username (str, optional): The admin user name of Extended ECM. Optional if otds_ticket is provided.
        password (str, optional): The admin password of Extended ECM. Optional if otds_ticket is provided.
        user_partition (str): Name of the OTDS partition for OTCS users. Default is "Content Server Members".
        resource_name (str, optional): Name of the OTDS resource for OTCS. Dault is "cs".
        default_license (str, optional): name of the default user license. Default is "X3".
        otds_ticket (str, optional): Authentication ticket of OTDS
    """

    # Initialize otcs_config as an empty dictionary
    otcs_config = {}

    if hostname:
        otcs_config["hostname"] = hostname
    else:
        otcs_config["hostname"] = "otcs-admin-0"

    if protocol:
        otcs_config["protocol"] = protocol
    else:
        otcs_config["protocol"] = "http"

    if port:
        otcs_config["port"] = port
    else:
        otcs_config["port"] = 8080

    otcs_config["publicUrl"] = public_url

    if username:
        otcs_config["username"] = username
    else:
        otcs_config["username"] = "admin"

    if password:
        otcs_config["password"] = password
    else:
        otcs_config["password"] = ""

    if user_partition:
        otcs_config["partition"] = user_partition
    else:
        otcs_config["partition"] = ""

    if resource_name:
        otcs_config["resource"] = resource_name
    else:
        otcs_config["resource"] = ""

    if default_license:
        otcs_config["license"] = default_license
    else:
        otcs_config["license"] = ""

    otcs_config["feme_uri"] = feme_uri

    otcs_base_url = protocol + "://" + otcs_config["hostname"]
    if str(port) not in ["80", "443"]:
        otcs_base_url += ":{}".format(port)
    otcs_config["baseUrl"] = otcs_base_url
    otcs_support_url = otcs_base_url + "/cssupport"
    otcs_config["supportUrl"] = otcs_support_url

    if public_url is None:
        public_url = otcs_base_url

    otcs_public_support_url = public_url + "/cssupport"
    otcs_config["supportPublicUrl"] = otcs_public_support_url

    otcs_config["configuredUrl"] = otcs_support_url + "/csconfigured"

    otcs_url = otcs_base_url + base_path
    otcs_config["csUrl"] = otcs_url
    otcs_public_url = public_url + base_path
    otcs_config["csPublicUrl"] = otcs_public_url

    otcs_rest_url = otcs_url + "/api"
    otcs_config["restUrl"] = otcs_rest_url

    otcs_config["isReady"] = otcs_rest_url + "/v1/ping"
    otcs_config["authenticationUrl"] = otcs_rest_url + "/v1/auth"
    otcs_config["serverInfoUrl"] = otcs_rest_url + "/v1/serverinfo"
    otcs_config["membersUrl"] = otcs_rest_url + "/v1/members"
    otcs_config["membersUrlv2"] = otcs_rest_url + "/v2/members"
    otcs_config["nodesUrl"] = otcs_rest_url + "/v1/nodes"
    otcs_config["nodesUrlv2"] = otcs_rest_url + "/v2/nodes"
    otcs_config["doctemplatesUrl"] = otcs_rest_url + "/v2/doctemplates"
    otcs_config["nicknameUrl"] = otcs_rest_url + "/v2/nicknames"
    otcs_config["importSettingsUrl"] = otcs_rest_url + "/v2/import/settings/admin"
    otcs_config["searchUrl"] = otcs_rest_url + "/v2/search"
    otcs_config["volumeUrl"] = otcs_rest_url + "/v2/volumes"
    otcs_config["externalSystemUrl"] = otcs_rest_url + "/v2/externalsystems"
    otcs_config["businessObjectsUrl"] = otcs_rest_url + "/v2/businessobjects"
    otcs_config["businessObjectTypesUrl"] = (
        otcs_rest_url + "/v2/businessobjecttypes"
    )
    otcs_config["businessObjectsSearchUrl"] = (
        otcs_rest_url + "/v2/forms/businessobjects/search"
    )
    otcs_config["businessWorkspaceTypesUrl"] = (
        otcs_rest_url + "/v2/businessworkspacetypes"
    )
    otcs_config["businessworkspacecreateform"] = (
        otcs_rest_url + "/v2/forms/businessworkspaces/create"
    )
    otcs_config["businessWorkspacesUrl"] = otcs_rest_url + "/v2/businessworkspaces"
    otcs_config["uniqueNamesUrl"] = otcs_rest_url + "/v2/uniquenames"
    otcs_config["favoritesUrl"] = otcs_rest_url + "/v2/members/favorites"
    otcs_config["webReportsUrl"] = otcs_rest_url + "/v1/webreports"
    otcs_config["csApplicationsUrl"] = otcs_rest_url + "/v2/csapplications"
    otcs_config["xEngProjectTemplateUrl"] = (
        otcs_rest_url + "/v2/xengcrt/projecttemplate"
    )
    otcs_config["rsisUrl"] = otcs_rest_url + "/v2/rsis"
    otcs_config["rsiSchedulesUrl"] = otcs_rest_url + "/v2/rsischedules"
    otcs_config["recordsManagementUrl"] = otcs_rest_url + "/v1/recordsmanagement"
    otcs_config["recordsManagementUrlv2"] = otcs_rest_url + "/v2/recordsmanagement"
    otcs_config["userSecurityUrl"] = otcs_rest_url + "/v2/members/usersecurity"
    otcs_config["physicalObjectsUrl"] = otcs_rest_url + "/v1/physicalobjects"
    otcs_config["securityClearancesUrl"] = otcs_rest_url + "/v1/securityclearances"
    otcs_config["holdsUrl"] = otcs_rest_url + "/v1/holds"
    otcs_config["holdsUrlv2"] = otcs_rest_url + "/v2/holds"
    otcs_config["validationUrl"] = otcs_rest_url + "/v1/validation/nodes/names"
    otcs_config["aiUrl"] = otcs_rest_url + "/v2/ai/nodes"
    otcs_config["recycleBinUrl"] = otcs_rest_url + "/v2/volumes/recyclebin"
    otcs_config["processUrl"] = otcs_rest_url + "/v2/processes"
    otcs_config["workflowUrl"] = otcs_rest_url + "/v2/workflows"
    otcs_config["docWorkflowUrl"] = otcs_rest_url + "/v2/docworkflows"
    otcs_config["draftProcessUrl"] = otcs_rest_url + "/v2/draftprocesses"
    otcs_config["draftProcessFormUrl"] = otcs_rest_url + "/v1/forms/draftprocesses"
    otcs_config["processTaskUrl"] = (
        otcs_rest_url + "/v1/forms/processes/tasks/update"
    )

    self._config = otcs_config
    self._otds_ticket = otds_ticket
    self._data = Data()
    self._thread_number = thread_number
    self._download_dir = download_dir
    self._semaphore = threading.BoundedSemaphore(value=thread_number)

add_document_version(node_id, file_url, file_name, mime_type='text/plain', description='')

Fetch a file from a URL or local filesystem and upload it as a new document version.

Parameters:

Name Type Description Default
node_id int

ID of the document to add add version to

required
file_url str

URL to download file or local file

required
file_name str

name of the file

required
mime_type str

mimeType of the file (default = text/plain)

'text/plain'
description str

description of the version (default = no description)

''

Returns: dict: Add version response or None if the upload fails.

Source code in pyxecm/otcs.py
def add_document_version(
    self,
    node_id: int,
    file_url: str,
    file_name: str,
    mime_type: str = "text/plain",
    description: str = "",
) -> dict | None:
    """Fetch a file from a URL or local filesystem and upload it as a new document version.

    Args:
        node_id (int): ID of the document to add add version to
        file_url (str): URL to download file or local file
        file_name (str): name of the file
        mime_type (str, optional): mimeType of the file (default = text/plain)
        description (str, optional): description of the version (default = no description)
    Returns:
        dict: Add version response or None if the upload fails.
    """

    # Desciption of a version cannot be longer than 255 characters in OTCS:
    if description and len(description) > 255:
        description = description[:255]

    if file_url.startswith("http"):
        # Download file from remote location specified by the file_url parameter
        # this must be a public place without authentication:
        logger.debug("Download file from URL -> %s", file_url)

        try:
            response = requests.get(
                url=file_url,
                timeout=None,
            )
            response.raise_for_status()
        except requests.exceptions.HTTPError as errh:
            logger.error("Http Error -> %s", errh.strerror)
            return None
        except requests.exceptions.ConnectionError as errc:
            logger.error("Error Connecting -> %s", errc.strerror)
            return None
        except requests.exceptions.Timeout as errt:
            logger.error("Timeout Error -> %s", errt.strerror)
            return None
        except requests.exceptions.RequestException as err:
            logger.error("Request error -> %s", err.strerror)
            return None

        logger.debug(
            "Successfully downloaded file -> %s; status code -> %s",
            file_url,
            response.status_code,
        )
        file_content = response.content

    elif os.path.exists(file_url):
        logger.debug("Upload local file -> %s", file_url)
        file_content = open(file=file_url, mode="rb")

    else:
        logger.warning("Cannot access -> %s", file_url)
        return None

    upload_post_data = {"description": description}
    upload_post_files = [("file", (f"{file_name}", file_content, mime_type))]

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/versions"

    # When we upload files using the 'files' parameter, the request must be encoded
    # as multipart/form-data, which allows binary data (like files) to be sent along
    # with other form data.
    # The requests library sets this header correctly if the 'files' parameter is provided.
    # So we just put the cookie in the header and trust the request library to add
    # the Content-Type = multipart/form-data :
    request_header = self.cookie()

    logger.debug(
        "Upload file -> '%s' with mime type -> '%s' as new version to document node with ID -> %s; calling -> %s",
        file_name,
        mime_type,
        node_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=upload_post_data,
        files=upload_post_files,
        timeout=None,
        failure_message="Failed to add file -> '{}' as new version to document with ID -> {}".format(
            file_url, node_id
        ),
    )

add_external_system_connection(connection_name, connection_type, as_url, base_url, username, password, authentication_method='BASIC', client_id=None, client_secret=None)

Add Extended ECM external system connection (e.g. SAP, Salesforce, SuccessFactors).

Parameters:

Name Type Description Default
connection_name str

Name of the connection

required
connection_type str

Type of the connection (HTTP, SF, SFInstance)

required
as_url str

Application URL of the external system

required
base_url str

Base URL of the external system

required
username str

username (used for BASIC authentication)

required
password str

password (used for BASIC authentication)

required
authentication_method str

either BASIC (using username and password) or OAUTH

'BASIC'
client_id str

OAUTH Client ID (only required if authenticationMethod = OAUTH)

None
client_secret str

OAUTH Client Secret (only required if authenticationMethod = OAUTH)

None

Returns: dict: External system Details or None if the REST call fails.

Source code in pyxecm/otcs.py
def add_external_system_connection(
    self,
    connection_name: str,
    connection_type: str,
    as_url: str,
    base_url: str,
    username: str,
    password: str,
    authentication_method: str = "BASIC",  # either BASIC or OAUTH
    client_id: str = None,
    client_secret: str = None,
) -> dict | None:
    """Add Extended ECM external system connection (e.g. SAP, Salesforce, SuccessFactors).

    Args:
        connection_name (str): Name of the connection
        connection_type (str): Type of the connection (HTTP, SF, SFInstance)
        as_url (str): Application URL of the external system
        base_url (str): Base URL of the external system
        username (str): username (used for BASIC authentication)
        password (str): password (used for BASIC authentication)
        authentication_method (str, optional): either BASIC (using username and password) or OAUTH
        client_id (str, optional): OAUTH Client ID (only required if authenticationMethod = OAUTH)
        client_secret (str, optional): OAUTH Client Secret (only required if authenticationMethod = OAUTH)
    Returns:
        dict: External system Details or None if the REST call fails.
    """

    external_system_post_body = {
        "external_system_name": connection_name,
        "conn_type": connection_type,
        "asurl": as_url,
        "baseurl": base_url,
        "username": username,
        "password": password,
    }

    if authentication_method == "OAUTH" and client_id and client_secret:
        external_system_post_body["authentication_method"] = str(
            authentication_method
        )
        external_system_post_body["client_id"] = str(client_id)
        external_system_post_body["client_secret"] = str(client_secret)

    request_url = self.config()["externalSystemUrl"]
    request_header = self.cookie()

    logger.debug(
        "Create external system connection -> '%s' of type -> '%s' with URL -> %s; calling -> %s",
        connection_name,
        connection_type,
        as_url,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=external_system_post_body,
        timeout=None,
        failure_message="Failed to create external system connection -> '{}'".format(
            connection_name
        ),
    )

add_favorite(node_id)

Add a favorite for the current (authenticated) user.

Parameters:

Name Type Description Default
node_id int

ID of the node.

required

Returns: dict: Request response or None if the favorite creation has failed.

Source code in pyxecm/otcs.py
def add_favorite(self, node_id: int) -> dict | None:
    """Add a favorite for the current (authenticated) user.

    Args:
        node_id (int): ID of the node.
    Returns:
        dict: Request response or None if the favorite creation has failed.
    """

    request_url = self.config()["favoritesUrl"] + "/" + str(node_id)
    request_header = self.request_form_header()

    logger.debug(
        "Adding favorite for node ID -> %s; calling -> %s", node_id, request_url
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        timeout=None,
        failure_message="Failed to add favorite for node ID -> {}".format(node_id),
    )

add_favorite_tab(tab_name, order)

Add a favorite tab for the current (authenticated) user.

Parameters:

Name Type Description Default
tab_name str

Name of the new tab.

required
order int

The order of the tab.

required

Returns: dict: Request response or None if the favorite tab creation has failed.

Source code in pyxecm/otcs.py
def add_favorite_tab(self, tab_name: str, order: int) -> dict | None:
    """Add a favorite tab for the current (authenticated) user.

    Args:
        tab_name (str): Name of the new tab.
        order (int): The order of the tab.
    Returns:
        dict: Request response or None if the favorite tab creation has failed.
    """

    favorite_tab_post_body = {"name": tab_name, "order": str(order)}

    request_url = self.config()["favoritesUrl"] + "/tabs"
    request_header = self.request_form_header()

    logger.debug("Adding favorite tab -> %s; calling -> %s", tab_name, request_url)

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=favorite_tab_post_body,
        timeout=None,
        failure_message="Failed to add favorite tab -> {}".format(tab_name),
    )

add_group(name)

Add Content Server group.

Parameters:

Name Type Description Default
name str

name of the group

required

Returns: dict: Group information or None if the group couldn't be created (e.g. because it exisits already).

Source code in pyxecm/otcs.py
def add_group(self, name: str) -> dict | None:
    """Add Content Server group.

    Args:
        name (str): name of the group
    Returns:
        dict: Group information or None if the group couldn't be created (e.g. because it exisits already).
    """

    group_post_body = {"type": 1, "name": name}

    request_url = self.config()["membersUrlv2"]
    request_header = self.request_form_header()

    logger.debug("Adding group -> '%s'; calling -> %s", name, request_url)
    logger.debug("Group Attributes -> %s", str(group_post_body))

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=group_post_body,
        timeout=None,
        failure_message="Failed to add group -> '{}'".format(name),
    )

add_group_member(member_id, group_id)

Add a user or group to a target group.

Parameters:

Name Type Description Default
member_id int

ID of the user or group to add.

required
group_id int

ID of the target group.

required

Returns: dict: Response or None if adding a the member fails.

Source code in pyxecm/otcs.py
def add_group_member(self, member_id: int, group_id: int) -> dict | None:
    """Add a user or group to a target group.

    Args:
        member_id (int): ID of the user or group to add.
        group_id (int): ID of the target group.
    Returns:
        dict: Response or None if adding a the member fails.
    """

    group_member_post_body = {"member_id": member_id}

    request_url = self.config()["membersUrlv2"] + "/" + str(group_id) + "/members"
    request_header = self.request_form_header()

    logger.debug(
        "Adding member with ID -> %s to group with ID -> %s; calling -> %s",
        str(member_id),
        str(group_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=group_member_post_body,
        timeout=None,
        failure_message="Failed to add member with ID -> {} to group with ID -> {}".format(
            member_id, group_id
        ),
    )

add_user(name, password, first_name, last_name, email, title, base_group, privileges=None)

Add Content Server user.

Parameters:

Name Type Description Default
name str

login name of the user

required
password str

password of the user

required
first_name str

first name of the user

required
last_name str

last name of the user

required
email str

email address of the user

required
title str

title of the user

required
base_group int

base group id of the user (e.g. department)

required
privileges list

values are Login, Public Access, Content Manager, Modify Users, Modify Groups, User Admin Rights, Grant Discovery, System Admin Rights

None

Returns: dict: User information or None if the user couldn't be created (e.g. because it exisits already).

Source code in pyxecm/otcs.py
def add_user(
    self,
    name: str,
    password: str,
    first_name: str,
    last_name: str,
    email: str,
    title: str,
    base_group: int,
    privileges: list | None = None,
) -> dict | None:
    """Add Content Server user.

    Args:
        name (str): login name of the user
        password (str): password of the user
        first_name (str): first name of the user
        last_name (str): last name of the user
        email (str): email address of the user
        title (str): title of the user
        base_group (int): base group id of the user (e.g. department)
        privileges (list, optional): values are Login, Public Access, Content Manager,
                                     Modify Users, Modify Groups, User Admin Rights,
                                     Grant Discovery, System Admin Rights
    Returns:
        dict: User information or None if the user couldn't be created (e.g. because it exisits already).
    """

    if privileges is None:
        privileges = ["Login", "Public Access"]

    user_post_body = {
        "type": 0,
        "name": name,
        "password": password,
        "first_name": first_name,
        "last_name": last_name,
        "business_email": email,
        "title": title,
        "group_id": base_group,
        "privilege_login": ("Login" in privileges),
        "privilege_public_access": ("Public Access" in privileges),
        "privilege_content_manager": ("Content Manager" in privileges),
        "privilege_modify_users": ("Modify Users" in privileges),
        "privilege_modify_groups": ("Modify Groups" in privileges),
        "privilege_user_admin_rights": ("User Admin Rights" in privileges),
        "privilege_grant_discovery": ("Grant Discovery" in privileges),
        "privilege_system_admin_rights": ("System Admin Rights" in privileges),
    }

    request_url = self.config()["membersUrlv2"]
    request_header = self.request_form_header()

    logger.debug("Add user -> '%s'; calling -> %s", name, request_url)

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=user_post_body,
        timeout=None,
        failure_message="Failed to add user -> '{}'".format(name),
    )

add_user_proxy(proxy_user_id, from_date=None, to_date=None)

Add a user as a proxy user to the current user. IMPORTANT: This method needs to be called as the user the proxy is acting for. Optional this method can be provided with a time span the proxy should be active. This method differentiates between the old (xGov) based implementation and the new Extended ECM platform one that was introduced with version 23.4.

Example payload for proxy user 19340 without time span: {"id":2545, "from_date": None, "to_date": None}

Example payload for proxy user 19340 with time span: {"id":2545, "from_date":"2023-03-15", "to_date":"2023-03-31"}

Parameters:

Name Type Description Default
user_id int

ID of the user

required
from_date str

start date for proxy (format YYYY-MM-DD)

None
to_date str

end date for proxy (format YYYY-MM-DD)

None

Returns: dict: Request response or None if call fails.

Source code in pyxecm/otcs.py
def add_user_proxy(
    self,
    proxy_user_id: int,
    from_date: str = None,
    to_date: str = None,
) -> dict | None:
    """Add a user as a proxy user to the current user.
       IMPORTANT: This method needs to be called as the user the proxy is acting for.
       Optional this method can be provided with a time span the proxy should be active.
       This method differentiates between the old (xGov) based
       implementation and the new Extended ECM platform one
       that was introduced with version 23.4.

       Example payload for proxy user 19340 without time span:
       {"id":2545, "from_date": None, "to_date": None}

       Example payload for proxy user 19340 with time span:
       {"id":2545, "from_date":"2023-03-15", "to_date":"2023-03-31"}

    Args:
        user_id (int): ID of the user
        from_date (str, optional): start date for proxy (format YYYY-MM-DD)
        to_date (str, optional): end date for proxy (format YYYY-MM-DD)
    Returns:
        dict: Request response or None if call fails.
    """

    version_number = self.get_server_version()
    # Split the version number by dot
    parts = version_number.split(".")
    # Take the first two parts and join them back with a dot
    stripped_version = ".".join(parts[:2])
    version_number = float(stripped_version)

    # for versions older than 23.4 we need to use
    # the legacy Extended ECM for Government Proxy
    # implementation:
    if version_number >= 23.4:
        post_dict = {}
        post_dict["id"] = proxy_user_id
        post_dict["from_date"] = from_date
        post_dict["to_date"] = to_date
        post_data = {"body": json.dumps(post_dict)}
        request_url = self.config()["membersUrlv2"] + "/proxies"
        logger.debug(
            "Assign proxy user with ID -> %s to current user; calling -> %s",
            proxy_user_id,
            request_url,
        )
    else:
        post_dict = {}
        if from_date and to_date:
            post_dict["from_date"] = from_date
            post_dict["to_date"] = to_date
        post_dict = {str(proxy_user_id): post_dict}
        post_data = {"add_proxy": json.dumps(post_dict)}
        request_url = self.config()["membersUrl"] + "/proxies"
        logger.debug(
            "Assign proxy user with ID -> %s to current user (legacy xGov); calling -> %s",
            proxy_user_id,
            request_url,
        )

    request_header = self.request_form_header()

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=post_data,
        timeout=None,
        failure_message="Failed to assign proxy user with ID -> {} to current user".format(
            proxy_user_id
        ),
    )

add_workspace_member(workspace_id, role_id, member_id, show_warning=True)

Add member to a workspace role. Check that the user/group is not yet a member.

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace

required
role_id int

ID of the role

required
member_id int

User ID or Group ID

required
show_warning bool

If True logs a warning if member is already in role

True

Returns: dict: Workspace Role Membership or None if the request fails.

Source code in pyxecm/otcs.py
def add_workspace_member(
    self, workspace_id: int, role_id: int, member_id: int, show_warning: bool = True
) -> dict | None:
    """Add member to a workspace role. Check that the user/group is not yet a member.

    Args:
        workspace_id (int): ID of the workspace
        role_id (int): ID of the role
        member_id (int): User ID or Group ID
        show_warning (bool, optional): If True logs a warning if member is already in role
    Returns:
        dict: Workspace Role Membership or None if the request fails.
    """

    logger.debug(
        "Check if user/group with ID -> %s is already in role with ID -> %s of workspace with ID -> %s",
        str(member_id),
        str(role_id),
        str(workspace_id),
    )

    workspace_members = self.get_workspace_members(
        workspace_id=workspace_id, role_id=role_id
    )

    if self.exist_result_item(workspace_members, "id", member_id):
        if show_warning:
            logger.warning(
                "User/group with ID -> %s is already a member of role with ID -> %s of workspace with ID -> %s",
                str(member_id),
                str(role_id),
                str(workspace_id),
            )
        return workspace_members

    add_workspace_member_post_data = {"id": str(member_id)}

    request_url = self.config()[
        "businessWorkspacesUrl"
    ] + "/{}/roles/{}/members".format(workspace_id, role_id)
    request_header = self.request_form_header()

    logger.debug(
        "Add user/group with ID -> %s to role with ID -> %s of workspace with ID -> %s; calling -> %s",
        str(member_id),
        str(role_id),
        str(workspace_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=add_workspace_member_post_data,
        timeout=None,
        failure_message="Failed to add user/group with ID -> {} to role with ID -> {} of workspace with ID -> {}".format(
            member_id, role_id, workspace_id
        ),
    )

apply_config(xml_file_path)

Apply Content Server administration settings from XML file

Parameters:

Name Type Description Default
xml_file_path str

name + path of the XML settings file

required

Returns: dict: Import response or None if the import fails. The field response["results"]["data"]["restart"] indicates if the settings require a restart of the OTCS services.

Source code in pyxecm/otcs.py
def apply_config(self, xml_file_path: str) -> dict | None:
    """Apply Content Server administration settings from XML file

    Args:
        xml_file_path (str): name + path of the XML settings file
    Returns:
        dict: Import response or None if the import fails.
              The field response["results"]["data"]["restart"] indicates if the settings
              require a restart of the OTCS services.
    """

    filename = os.path.basename(xml_file_path)

    if not os.path.exists(xml_file_path):
        logger.error(
            "The admin settings file -> '%s' does not exist in path -> '%s'!",
            filename,
            os.path.dirname(xml_file_path),
        )
        return None

    llconfig_file = {
        "file": (filename, open(file=xml_file_path, encoding="utf-8"), "text/xml")
    }

    request_url = self.config()["importSettingsUrl"]
    request_header = self._cookie

    logger.debug(
        "Applying admin settings from file -> '%s'; calling -> %s",
        xml_file_path,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        files=llconfig_file,
        timeout=None,
        success_message="Admin settings in file -> '{}' have been applied".format(
            xml_file_path
        ),
        failure_message="Failed to import settings file -> '{}'".format(
            xml_file_path
        ),
    )

apply_filter(node, current_depth=0, filter_depth=None, filter_subtypes=None, filter_category=None, filter_attributes=None)

Check all defined filters for the given node.

Parameters:

Name Type Description Default
node dict

Current OTCS Node

required
filter_depth int | None

Additive filter criterium for path depth. Defaults to None = filter not active.

None
filter_subtype list | None

Additive filter criterium for workspace type. Defaults to None = filter not active.

required
filter_category str | None

Additive filter criterium for workspace category. Defaults to None = filter not active.

None
filter_attributes dict | list | None

description. Defaults to None.

None

Returns:

Name Type Description
bool bool

Only for nodes that comply with ALL provided filters True is returned. Otherwise False.

Source code in pyxecm/otcs.py
def apply_filter(
    self,
    node: dict,
    current_depth: int = 0,
    filter_depth: int | None = None,
    filter_subtypes: list | None = None,
    filter_category: str | None = None,
    filter_attributes: dict | list | None = None,
) -> bool:
    """Check all defined filters for the given node.

    Args:
        node (dict): Current OTCS Node
        filter_depth (int | None, optional): Additive filter criterium for path depth. Defaults to None = filter not active.
        filter_subtype (list | None, optional): Additive filter criterium for workspace type. Defaults to None = filter not active.
        filter_category (str | None, optional): Additive filter criterium for workspace category. Defaults to None = filter not active.
        filter_attributes (dict | list | None, optional): _description_. Defaults to None.

    Returns:
        bool: Only for nodes that comply with ALL provided filters True is returned. Otherwise False.
    """

    if not node or not "type" in node or not "id" in node:
        logger.error("Illegal node!")
        return False

    if filter_subtypes and not node["type"] in filter_subtypes:
        logger.info(
            "Node type -> '%s' is not in filter node types -> %s. Node -> '%s' failed filter test.",
            node["type"],
            filter_subtypes,
            node["name"],
        )
        return False

    if filter_depth is not None and filter_depth != current_depth:
        logger.info(
            "Node is in depth -> %s which is different from filter depth -> %s. Node -> '%s' failed filter test.",
            current_depth,
            filter_depth,
            node["name"],
        )
        return False

    if filter_category:
        category_names = self.get_node_category_names(node_id=node["id"])
        if not category_names or filter_category not in category_names:
            logger.info(
                "Node categories -> %s do not include filter category -> '%s'. Node -> '%s' failed filter test.",
                category_names,
                filter_category,
                node["name"],
            )
            return False
        if filter_attributes:
            if isinstance(filter_attributes, dict):
                filter_attributes = [filter_attributes]
            for filter_attribute in filter_attributes:
                filter_category_name = filter_attribute.get(
                    "category", filter_category
                )
                if not filter_category_name:
                    logger.error(
                        "Attribute filter -> %s is missing category name!",
                        str(filter_attribute),
                    )
                    continue
                filter_set_name = filter_attribute.get("set", None)
                filter_attribute_name = filter_attribute.get("attribute", None)
                if not filter_attribute_name:
                    logger.error(
                        "Attribute filter -> %s is missing attribute name!",
                        str(filter_attribute),
                    )
                    continue
                filter_row = filter_attribute.get("row", None)
                filter_value = filter_attribute.get("value", None)
                actual_value = self.get_category_value_by_name(
                    node_id=node["id"],
                    category_name=filter_category_name,
                    set_name=filter_set_name,
                    attribute_name=filter_attribute_name,
                    set_row=filter_row,
                )
                # Both actual value and filter value can be strings or list of strings.
                # So we need to handle a couple of cases here:

                # Case 1: Data source delivers a list and filter value is a scalar value (int, str, float)
                if isinstance(actual_value, list) and isinstance(
                    filter_value, (str, int, float)
                ):
                    if filter_value not in actual_value:
                        return False
                # Case 2: Data source delivers a scalar value and filter value is a list
                elif isinstance(actual_value, (str, int, float)) and isinstance(
                    filter_value, list
                ):
                    if actual_value not in filter_value:
                        return False
                # Case 3: Both, filter and actual value are lists:
                elif isinstance(actual_value, list) and isinstance(
                    filter_value, list
                ):
                    # check if there's an non-empty intersetion set of both lists:
                    if not set(actual_value) & set(filter_value):
                        return False
                elif isinstance(actual_value, (str, int, float)) and isinstance(
                    filter_value, (str, int, float)
                ):
                    if actual_value != filter_value:
                        return False
                else:
                    return False

    return True

assign_category(node_id, category_id, inheritance=False, apply_to_sub_items=False, apply_action='add_upgrade', add_version=False, clear_existing_categories=False)

Assign a category to a node. Optionally turn on inheritance and apply category to sub-items (if node_id is a container / folder / workspace). If the category is already assigned to the node this method will throw an error.

Parameters:

Name Type Description Default
node_id int

node ID to apply the category to

required
category_id list

ID of the category definition object

required
inheritance bool

turn on inheritance for the category (this makes only sense if the node is a container like a folder or workspace)

False
apply_to_sub_items bool

if True the category is applied to the item and all its sub-items if False the category is only applied to the item

False
apply_action str

supported values are "add", "add_upgrade", "upgrade", "replace", "delete", "none", None

'add_upgrade'
add_version bool

if a document version should be added for the category change (default = False)

False
clear_existing_categories bool

whether or not existing (other) categories should be removed (default = False)

False

Returns: bool: True = success, False = error

Source code in pyxecm/otcs.py
def assign_category(
    self,
    node_id: int,
    category_id: list,
    inheritance: bool = False,
    apply_to_sub_items: bool = False,
    apply_action: str = "add_upgrade",
    add_version: bool = False,
    clear_existing_categories: bool = False,
) -> bool:
    """Assign a category to a node. Optionally turn on inheritance and apply
       category to sub-items (if node_id is a container / folder / workspace).
       If the category is already assigned to the node this method will
       throw an error.

    Args:
        node_id (int): node ID to apply the category to
        category_id (list): ID of the category definition object
        inheritance (bool): turn on inheritance for the category
                            (this makes only sense if the node is a container like a folder or workspace)
        apply_to_sub_items (bool, optional): if True the category is applied to
                                                the item and all its sub-items
                                                if False the category is only applied
                                                to the item
        apply_action (str, optional): supported values are "add", "add_upgrade", "upgrade", "replace", "delete", "none", None
        add_version (bool, optional): if a document version should be added for the category change (default = False)
        clear_existing_categories (bool, optional): whether or not existing (other) categories should be removed (default = False)
    Returns:
        bool: True = success, False = error
    """

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/categories"
    request_header = self.request_form_header()

    #
    # 1. Assign Category to Node if not yet assigned:
    #

    existing_category_ids = self.get_node_category_ids(node_id)
    if not category_id in existing_category_ids:
        logger.debug(
            "Category with ID -> %s is not yet assigned to node ID -> %s. Assigning it now...",
            str(category_id),
            str(node_id),
        )
        category_post_data = {
            "category_id": category_id,
        }

        logger.debug(
            "Assign category with ID -> %s to item with ID -> %s; calling -> %s",
            str(category_id),
            str(node_id),
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=category_post_data,
            timeout=None,
            failure_message="Failed to assign category with ID -> {} to node with ID -> {}".format(
                category_id, node_id
            ),
            parse_request_response=False,
        )

        if not response or not response.ok:
            return False

    #
    # 2. Set Inheritance
    #

    response = self.set_category_inheritance(
        node_id=node_id, category_id=category_id, enable=inheritance
    )
    if not response:
        return False

    #
    # 3. Apply to sub-items
    #

    if apply_to_sub_items:
        request_url_apply_sub_items = request_url + "/apply"

        category_post_data = {
            "categories": [{"id": category_id, "action": apply_action}],
            "add_version": add_version,
            "clear_existing_categories": clear_existing_categories,
        }

        # we need to wrap the body of this POST call into a "body"
        # tag. This is documented worngly on developer.opentext.com
        response = self.do_request(
            url=request_url_apply_sub_items,
            method="POST",
            headers=request_header,
            data={"body": json.dumps(category_post_data)},
            timeout=None,
            failure_message="Failed to apply category with ID -> {} to sub-items of node with ID -> {}".format(
                category_id, node_id
            ),
            parse_request_response=False,
        )

        if not response or not response.ok:
            return False

    return True

assign_classification(node_id, classifications, apply_to_sub_items=False)

Assign one or multiple classifications to an Extended ECM item

Parameters:

Name Type Description Default
node_id int

node ID of the Extended ECM item

required
classifications list

list of classification item IDs

required
apply_to_sub_items bool

if True the classification is applied to the item and all its sub-items if False the classification is only applied to the item

False

Returns: dict: Response of the request or None if the assignment of the classification has failed.

Source code in pyxecm/otcs.py
def assign_classification(
    self, node_id: int, classifications: list, apply_to_sub_items: bool = False
) -> dict | None:
    """Assign one or multiple classifications to an Extended ECM item

    Args:
        node_id (int): node ID of the Extended ECM item
        classifications (list): list of classification item IDs
        apply_to_sub_items (bool, optional): if True the classification is applied to
                                                the item and all its sub-items
                                                if False the classification is only applied
                                                to the item
    Returns:
        dict: Response of the request or None if the assignment of the classification has failed.
    """

    # the REST API expects a list of dict elements with "id" and the actual IDs
    classification_list = []
    for classification in classifications:
        classification_list.append({"id": classification})

    classification_post_data = {
        "class_id": classification_list,
        "apply_to_sub_items": apply_to_sub_items,
    }

    request_url = (
        self.config()["nodesUrl"] + "/" + str(node_id) + "/classifications"
    )

    request_header = self.request_form_header()

    logger.debug(
        "Assign classifications with IDs -> %s to item with ID -> %s; calling -> %s",
        str(classifications),
        str(node_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=classification_post_data,
        timeout=None,
        failure_message="Failed to assign classifications with IDs -> {} to item with ID -> {}".format(
            classifications, node_id
        ),
    )

assign_item_to_user_group(node_id, subject, instruction, assignees)

Assign an Extended ECM item to users and groups. This is a function used by Extended ECM for Government.

Parameters:

Name Type Description Default
node_id int

node ID of the Extended ECM item (e.g. a workspace or a document)

required
subject str

title / subject of the assignment

required
instructions str

more detailed description or instructions for the assignment

required
assignees list

list of IDs of users or groups

required

Returns: dict: Response of the request or None if the assignment has failed.

Source code in pyxecm/otcs.py
def assign_item_to_user_group(
    self, node_id: int, subject: str, instruction: str, assignees: list
) -> dict | None:
    """Assign an Extended ECM item to users and groups. This is a function used by
       Extended ECM for Government.

    Args:
        node_id (int): node ID of the Extended ECM item (e.g. a workspace or a document)
        subject (str): title / subject of the assignment
        instructions (str): more detailed description or instructions for the assignment
        assignees (list): list of IDs of users or groups
    Returns:
        dict: Response of the request or None if the assignment has failed.
    """

    assignment_post_data = {
        "subject": subject,
        "instruction": instruction,
        "assignees": assignees,
    }

    request_url = (
        self.config()["nodesUrlv2"] + "/" + str(node_id) + "/xgovassignments"
    )

    request_header = self.request_form_header()

    logger.debug(
        "Assign item with ID -> %s to assignees -> %s (subject -> '%s'); calling -> %s",
        str(node_id),
        str(assignees),
        subject,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data={"add_assignment": json.dumps(assignment_post_data)},
        timeout=None,
        failure_message="Failed to assign item with ID -> {} to assignees -> {} (subject -> '{}')".format(
            node_id, assignees, subject
        ),
    )

assign_permission(node_id, assignee_type, assignee, permissions, apply_to=0)

Assign permissions for Extended ECM item to a user or group.

Parameters:

Name Type Description Default
node_id int

node ID of the Extended ECM item

required
assignee_type str

this can be either "owner", "group" (for owner group), "public", or "custom" (assigned access)

required
assignee int

ID of user or group ("right ID"). If 0 and assigneeType is "owner" or "group" then it is assumed that the owner and owner group should not be changed.

required
permissions list

list of permissions - potential elements: "see" "see_contents" "modify" "edit_attributes" "add_items" "reserve" "add_major_version" "delete_versions" "delete" "edit_permissions"

required
apply_to int

elements to apply permissions to - potential values: 0 = this item (default) 1 = sub-items 2 = This item and sub-items 3 = This item and immediate sub-items

0

Returns: dict: Response of the request or None if the assignment of permissions has failed.

Source code in pyxecm/otcs.py
def assign_permission(
    self,
    node_id: int,
    assignee_type: str,
    assignee: int,
    permissions: list,
    apply_to: int = 0,
) -> dict | None:
    """Assign permissions for Extended ECM item to a user or group.

    Args:
        node_id (int): node ID of the Extended ECM item
        assignee_type (str): this can be either "owner", "group" (for owner group),
                                "public", or "custom" (assigned access)
        assignee (int): ID of user or group ("right ID"). If 0 and assigneeType
                            is "owner" or "group" then it is assumed that the owner and
                            owner group should not be changed.
        permissions (list): list of permissions - potential elements:
                            "see"
                            "see_contents"
                            "modify"
                            "edit_attributes"
                            "add_items"
                            "reserve"
                            "add_major_version"
                            "delete_versions"
                            "delete"
                            "edit_permissions"
        apply_to (int, optional): elements to apply permissions to - potential values:
                             0 = this item (default)
                             1 = sub-items
                             2 = This item and sub-items
                             3 = This item and immediate sub-items
    Returns:
        dict: Response of the request or None if the assignment of permissions has failed.
    """

    if not assignee_type or not assignee_type in [
        "owner",
        "group",
        "public",
        "custom",
    ]:
        logger.error(
            "Missing or wrong assignee type. Needs to be owner, group, public or custom!"
        )
        return None
    if assignee_type == "custom" and not assignee:
        logger.error("Missing permission assignee!")
        return None

    permission_post_data = {
        "permissions": permissions,
        "apply_to": apply_to,
    }

    # Assignees can be specified for owner and group and must be specified for custom:
    #
    if assignee:
        permission_post_data["right_id"] = assignee

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "/permissions/"
        + assignee_type
    )

    request_header = self.request_form_header()

    logger.debug(
        "Assign permissions -> %s to item with ID -> %s; assignee type -> '%s'; calling -> %s",
        str(permissions),
        str(node_id),
        assignee_type,
        request_url,
    )

    if assignee_type == "custom":
        # Custom also has a REST POST - we prefer this one as to
        # also allows to add a new assigned permission (user or group):
        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data={"body": json.dumps(permission_post_data)},
            timeout=None,
            failure_message="Failed to assign custom permissions -> {} to item with ID -> {}".format(
                permissions, node_id
            ),
        )
    else:
        # Owner, Owner Group and Public require REST PUT:
        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data={"body": json.dumps(permission_post_data)},
            timeout=None,
            failure_message="Failed to assign stadard permissions -> {} to item with ID -> {}".format(
                permissions, node_id
            ),
        )

assign_rm_classification(node_id, rm_classification, apply_to_sub_items=False)

Assign a RM classification to an Extended ECM item Args: node_id (int): node ID of the Extended ECM item rm_classification (int): Records Management classification ID apply_to_sub_items (bool, optional): if True the RM classification is applied to the item and all its sub-items if False the RM classification is only applied to the item Returns: dict: Response of the request or None if the assignment of the RM classification has failed.

Source code in pyxecm/otcs.py
def assign_rm_classification(
    self, node_id: int, rm_classification: int, apply_to_sub_items: bool = False
) -> dict | None:
    """Assign a RM classification to an Extended ECM item
    Args:
        node_id (int): node ID of the Extended ECM item
        rm_classification (int): Records Management classification ID
        apply_to_sub_items (bool, optional): if True the RM classification is applied to
                                                the item and all its sub-items
                                                if False the RM classification is only applied
                                                to the item
    Returns:
        dict: Response of the request or None if the assignment of the RM classification has failed.
    """

    rm_classification_post_data = {
        "class_id": rm_classification,
        "apply_to_sub_items": apply_to_sub_items,
    }

    request_url = (
        self.config()["nodesUrl"] + "/" + str(node_id) + "/rmclassifications"
    )

    request_header = self.request_form_header()

    logger.debug(
        "Assign RM classifications with ID -> %s to item with ID -> %s; calling -> %s",
        str(rm_classification),
        str(node_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=rm_classification_post_data,
        timeout=None,
        failure_message="Failed to assign RM classifications with ID -> {} to item with ID -> {}".format(
            rm_classification, node_id
        ),
    )

assign_user_security_clearance(user_id, security_clearance)

Assign a Security Clearance level to an Extended ECM user

Parameters:

Name Type Description Default
user_id int

ID of the user

required
security_clearance int

security clearance level to be set

required

Returns: dict: REST response or None if the REST call fails.

Source code in pyxecm/otcs.py
def assign_user_security_clearance(
    self, user_id: int, security_clearance: int
) -> dict | None:
    """Assign a Security Clearance level to an Extended ECM user

    Args:
        user_id (int): ID of the user
        security_clearance (int): security clearance level to be set
    Returns:
        dict: REST response or None if the REST call fails.
    """

    assign_user_security_clearance_post_data = {
        "securityLevel": security_clearance,
    }

    request_url = self.config()[
        "userSecurityUrl"
    ] + "/{}/securityclearancelevel".format(user_id)
    request_header = self.request_form_header()

    logger.debug(
        "Assign security clearance -> %s to user with ID -> %s; calling -> %s",
        str(security_clearance),
        str(user_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=assign_user_security_clearance_post_data,
        timeout=None,
        failure_message="Failed to assign security clearance -> {} to user with ID -> {}".format(
            security_clearance, user_id
        ),
    )

assign_user_supplemental_markings(user_id, supplemental_markings)

Assign a list of Supplemental Markings to a user

Parameters:

Name Type Description Default
user_id int

ID of the user

required
supplemental_markings list of strings

list of Supplemental Markings to be set

required

Returns: dict: REST response or None if the REST call fails.

Source code in pyxecm/otcs.py
def assign_user_supplemental_markings(
    self, user_id: int, supplemental_markings: list
) -> dict | None:
    """Assign a list of Supplemental Markings to a user

    Args:
        user_id (int): ID of the user
        supplemental_markings (list of strings): list of Supplemental Markings to be set
    Returns:
        dict: REST response or None if the REST call fails.
    """

    assign_user_supplemental_markings_post_data = {
        "suppMarks": supplemental_markings,
    }

    request_url = self.config()[
        "userSecurityUrl"
    ] + "/{}/supplementalmarkings".format(user_id)
    request_header = self.request_form_header()

    logger.debug(
        "Assign supplemental markings -> %s to user with ID -> %s; calling -> %s",
        str(supplemental_markings),
        str(user_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=assign_user_supplemental_markings_post_data,
        timeout=None,
        failure_message="Failed to assign supplemental markings -> {} to user with ID -> {}".format(
            supplemental_markings, user_id
        ),
    )

assign_workspace_permissions(workspace_id, role_id, permissions, apply_to=2)

Update permissions of a workspace role Args: workspace_id (int): ID of the workspace role_id (int): ID of the role permissions (list): List of permissions - potential elements: "see" "see_contents" "modify" "edit_attributes" "add_items" "reserve" "add_major_version" "delete_versions" "delete" "edit_permissions" apply_to (int, optional): Items to apply the permission change. Possible values: 0 = this item 1 = sub-items 2 = This item and sub-items (default) 3 = This item and immediate sub-items Returns: dict: Workspace Role Membership or None if the request fails.

Source code in pyxecm/otcs.py
def assign_workspace_permissions(
    self, workspace_id: int, role_id: int, permissions: list, apply_to: int = 2
) -> dict | None:
    """Update permissions of a workspace role
    Args:
        workspace_id (int): ID of the workspace
        role_id (int): ID of the role
        permissions (list): List of permissions - potential elements:
                            "see"
                            "see_contents"
                            "modify"
                            "edit_attributes"
                            "add_items"
                            "reserve"
                            "add_major_version"
                            "delete_versions"
                            "delete"
                            "edit_permissions"
        apply_to (int, optional):  Items to apply the permission change. Possible values:
                                   0 = this item
                                   1 = sub-items
                                   2 = This item and sub-items (default)
                                   3 = This item and immediate sub-items
    Returns:
        dict: Workspace Role Membership or None if the request fails.
    """

    request_url = self.config()["businessWorkspacesUrl"] + "/{}/roles/{}".format(
        workspace_id, role_id
    )

    request_header = self.request_form_header()

    logger.debug(
        "Updating Permissions of role with ID -> %s of workspace with ID -> %s with permissions -> %s; calling -> %s",
        str(role_id),
        str(workspace_id),
        str(permissions),
        request_url,
    )

    permission_put_data = {
        "permissions": permissions,
        "apply_to": apply_to,
    }

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data={"body": json.dumps(permission_put_data)},
        timeout=None,
        failure_message="Failed to update permissions for role with ID -> {} of workspace with ID -> {}".format(
            role_id, workspace_id
        ),
    )

authenticate(revalidate=False, wait_for_ready=True)

Authenticates at Content Server and retrieve OTCS Ticket.

Parameters:

Name Type Description Default
revalidate bool

determinse if a re-athentication is enforced (e.g. if session has timed out with 401 error) By default we use the OTDS ticket (if exists) for the authentication with OTCS. This switch allows the forced usage of username / password for the authentication.

False
wait_for_ready bool

whether or not to wait for the OTCS service to be "ready". Default is True. If you want authentication to fail fast then set it to False.

True

Returns: dict: Cookie information of None in case of an error. Also stores cookie information in self._cookie

Source code in pyxecm/otcs.py
def authenticate(
    self, revalidate: bool = False, wait_for_ready: bool = True
) -> dict | None:
    """Authenticates at Content Server and retrieve OTCS Ticket.

    Args:
        revalidate (bool, optional): determinse if a re-athentication is enforced
                                     (e.g. if session has timed out with 401 error)
                                     By default we use the OTDS ticket (if exists) for the authentication with OTCS.
                                     This switch allows the forced usage of username / password for the authentication.
        wait_for_ready (bool, optional): whether or not to wait for the OTCS service to be "ready".
                                         Default is True. If you want authentication to fail fast then set it to False.
    Returns:
        dict: Cookie information of None in case of an error.
              Also stores cookie information in self._cookie
    """

    # Already authenticated and session still valid?
    if self._cookie and not revalidate:
        logger.debug(
            "Session still valid - return existing cookie -> %s",
            str(self._cookie),
        )
        return self._cookie

    otcs_ticket = None

    if wait_for_ready:
        logger.debug("Wait for OTCS to be ready...")
        while not self.is_ready():
            logger.debug(
                "OTCS is not ready to receive requests yet. Waiting additional 30 seconds..."
            )
            time.sleep(30)

    request_url = self.config()["authenticationUrl"]

    if self._otds_ticket and not revalidate:
        logger.debug(
            "Requesting OTCS ticket with OTDS ticket; calling -> %s",
            request_url,
        )
        request_header = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json",
            "OTDSTicket": self._otds_ticket,
        }

        try:
            response = requests.get(
                url=request_url, headers=request_header, timeout=10
            )
            if response.ok:
                otcs_ticket = response.headers.get("OTCSTicket")

        except requests.exceptions.RequestException as exception:
            logger.warning(
                "Unable to connect to -> %s; error -> %s",
                request_url,
                exception.strerror,
            )

    # Check if previous authentication was not successful.
    # Then we do the normal username + password authentication:
    if not otcs_ticket:
        logger.debug(
            "Requesting OTCS ticket with User/Password; calling -> %s",
            request_url,
        )

        response = None
        try:
            response = requests.post(
                url=request_url,
                data=self.credentials(),  # this includes username + password
                headers=REQUEST_FORM_HEADERS,
                timeout=REQUEST_TIMEOUT,
            )
        except requests.exceptions.RequestException as exception:
            logger.warning(
                "Unable to connect to -> %s; error -> %s",
                request_url,
                exception.strerror,
            )
            logger.warning("OTCS service may not be ready yet.")
            return None

        if response.ok:
            authenticate_dict = self.parse_request_response(
                response, "This can be normal during restart", False
            )
            if not authenticate_dict:
                return None
            else:
                otcs_ticket = authenticate_dict["ticket"]
                logger.debug("Ticket -> %s", otcs_ticket)
        else:
            logger.error(
                "Failed to request an OTCS ticket; error -> %s", response.text
            )
            return None

    # Store authentication ticket:
    self._cookie = {"otcsticket": otcs_ticket, "LLCookie": otcs_ticket}
    self._otcs_ticket = otcs_ticket

    return self._cookie

base_url()

Returns the base URL of Extended ECM

Returns:

Name Type Description
str str

base URL

Source code in pyxecm/otcs.py
def base_url(self) -> str:
    """Returns the base URL of Extended ECM

    Returns:
        str: base URL
    """
    return self.config()["baseUrl"]

check_node_name(parent_id, node_name)

Check if a node with a given name does already exist under a given parent node.

Parameters:

Name Type Description Default
parent_id int

ID of the parent location

required
node_name str

name of the new node

required

Returns: dict | None: if response["results"] contains an element then the node with the name does exist. if not response["results"] then the node with the given name does not exist None in case an error occured

Source code in pyxecm/otcs.py
def check_node_name(self, parent_id: int, node_name: str) -> dict | None:
    """Check if a node with a given name does already exist under a given parent node.

    Args:
        parent_id (int): ID of the parent location
        node_name (str): name of the new node
    Returns:
        dict | None: if response["results"] contains an element then the node with the name does exist.
                     if not response["results"] then the node with the given name does not exist
                     None in case an error occured
    """

    request_url = self.config()["validationUrl"]
    request_header = self.request_form_header()

    logger.debug(
        "Check if node with name -> '%s' can be created in parent with ID -> %s; calling -> %s",
        node_name,
        str(parent_id),
        request_url,
    )

    check_node_name_post_data = {"parent_id": parent_id, "names": [node_name]}

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data={"body": json.dumps(check_node_name_post_data)},
        timeout=None,
        failure_message="Failed to check if node name -> '{}' can be created in parent with ID -> {}".format(
            node_name, parent_id
        ),
    )

check_workspace_aviator(workspace_id)

Check if Content Aviator is enabled for a workspace

Parameters:

Name Type Description Default
workspace_id int

node ID of the workspace

required

Returns: bool: True if aviator is enabled, False otherwise

Source code in pyxecm/otcs.py
def check_workspace_aviator(
    self,
    workspace_id: int,
) -> bool:
    """Check if Content Aviator is enabled for a workspace

    Args:
        workspace_id (int): node ID of the workspace
    Returns:
        bool: True if aviator is enabled, False otherwise
    """

    response = self.get_node_actions(
        node_id=workspace_id, filter_actions=["disableai", "enableai"]
    )
    result_data = self.get_result_value(
        response=response,
        key=str(workspace_id),
    )
    if result_data and "data" in result_data:
        data = result_data["data"]
        if "disableai" in data:
            logger.debug(
                "Aviator is enabled for workspace with ID -> %s", str(workspace_id)
            )
            return True
        elif "enableai" in data:
            logger.debug(
                "Aviator is disabled for workspace with ID -> %s", str(workspace_id)
            )

    return False

config()

Returns the configuration dictionary

Returns:

Name Type Description
dict dict

Configuration dictionary

Source code in pyxecm/otcs.py
def config(self) -> dict:
    """Returns the configuration dictionary

    Returns:
        dict: Configuration dictionary
    """
    return self._config

convert_permission_string_to_permission_value(permissions)

Converts a list of permission names (strongs) to a bit-mask.

Parameters:

Name Type Description Default
permissions list

List of permission names - see conversion variable below.

required

Returns: int: bit-encoded permission value

Source code in pyxecm/otcs.py
def convert_permission_string_to_permission_value(self, permissions: list) -> int:
    """Converts a list of permission names (strongs) to a bit-mask.

    Args:
        permissions (list): List of permission names - see conversion variable below.
    Returns:
        int: bit-encoded permission value
    """

    conversion = {
        "see": 130,  # Bits 2 and 8
        "see_contents": 36865,  # Bit 17
        "modify": 65536,  # Bit 18
        "edit_attributes": 131072,  # Bit 19
        "add_items": 4,  # Bit 3
        "reserve": 8192,  # Bit 14
        "add_major_version": 4194304,  # Bit 23
        "delete_versions": 16384,  # Bit 15
        "delete": 8,  # Bit 4
        "edit_permissions": 16,  # Bit 5
    }

    permission_value = 0

    for permission in permissions:
        if not conversion.get(permission):
            logger.error("Illegal permission value -> %s", str(permission))
            return 0
        permission_value += conversion[permission]

    return permission_value

convert_permission_value_to_permission_string(permission_value)

Converts a bit-encoded permission value to a list of permission names (strings).

Parameters:

Name Type Description Default
permission_value int

bit-encoded permission value

required

Returns: list: list of permission names

Source code in pyxecm/otcs.py
def convert_permission_value_to_permission_string(
    self, permission_value: int
) -> list:
    """Converts a bit-encoded permission value to a list of permission names (strings).

    Args:
        permission_value (int): bit-encoded permission value
    Returns:
        list: list of permission names
    """

    conversion = {
        "see": 130,  # Bits 2 and 8
        "see_contents": 36865,  # Bit 17
        "modify": 65536,  # Bit 18
        "edit_attributes": 131072,  # Bit 19
        "add_items": 4,  # Bit 3
        "reserve": 8192,  # Bit 14
        "add_major_version": 4194304,  # Bit 23
        "delete_versions": 16384,  # Bit 15
        "delete": 8,  # Bit 4
        "edit_permissions": 16,  # Bit 5
    }

    permissions = []

    for key, value in conversion.items():
        if permission_value & value:  # binary and
            permissions.append(key)

    return permissions

cookie()

Returns the login cookie of Extended ECM. This is set by the authenticate() method

Returns:

Name Type Description
dict dict

Estended ECM cookie

Source code in pyxecm/otcs.py
def cookie(self) -> dict:
    """Returns the login cookie of Extended ECM.
       This is set by the authenticate() method

    Returns:
        dict: Estended ECM cookie
    """
    return self._cookie

create_document_from_template(template_id, parent_id, classification_id, category_data, doc_name, doc_desciption='')

Create a document based on a document template

Parameters:

Name Type Description Default
template_id int

node ID of the document template

required
parent_id int

node ID of the target location (parent)

required
classification_id int

node ID of the classification

required
category_data dict

metadata / category data Example: category ID = 12508 { "12508": { "12508_2": "Draft", # Text drop-down "12508_3": 8559, # user ID "12508_4": "2023-05-10", # date "12508_6": 7357, # user ID "12508_7": "2023-05-11", # date "12508_5": True, # checkbox / bool "12508_8": "EN", # text drop-down "12508_9": "MS Word", # text drop-down } }

required
doc_name str

Name of the item to create.

required
doc_description str

Description of the item to create.

required
Source code in pyxecm/otcs.py
def create_document_from_template(
    self,
    template_id: int,
    parent_id: int,
    classification_id: int,
    category_data: dict | None,
    doc_name: str,
    doc_desciption: str = "",
) -> dict | None:
    """Create a document based on a document template

    Args:
        template_id (int): node ID of the document template
        parent_id (int): node ID of the target location (parent)
        classification_id (int): node ID of the classification
        category_data (dict): metadata / category data
                                Example: category ID = 12508
                                {
                                    "12508": {
                                        "12508_2": "Draft",         # Text drop-down
                                        "12508_3": 8559,            # user ID
                                        "12508_4": "2023-05-10",    # date
                                        "12508_6": 7357,            # user ID
                                        "12508_7": "2023-05-11",    # date
                                        "12508_5": True,            # checkbox / bool
                                        "12508_8": "EN",            # text drop-down
                                        "12508_9": "MS Word",       # text drop-down
                                    }
                                }
        doc_name (str): Name of the item to create.
        doc_description (str, optional): Description of the item to create.
    """

    create_document_post_data = {
        "template_id": template_id,
        "parent_id": parent_id,
        "name": doc_name,
        "description": doc_desciption,
        "type": 144,
        "roles": {
            "categories": category_data,
            "classifications": {"create_id": [classification_id], "id": []},
        },
    }

    request_url = self.config()["doctemplatesUrl"]
    request_header = self.request_form_header()

    logger.debug(
        "Create document -> '%s' from template with ID -> %s in target location with ID -> %s with classification ID -> %s; calling -> %s",
        doc_name,
        str(template_id),
        str(parent_id),
        str(classification_id),
        request_url,
    )

    # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        # this seems to only work with a "body" tag and is different form the documentation
        # on developer.opentext.com
        data={"body": json.dumps(create_document_post_data)},
        timeout=None,
        failure_message="Failed to create document -> '{}'".format(doc_name),
    )

create_draft_process(workflow_id, documents)

Initiate a draft process. This is the first step to start a process (workflow instance)

Parameters:

Name Type Description Default
workflow_id int

Node ID of the workflow maps

required
documents list

node IDs of the attachmewnt documents

required

Returns:

Name Type Description
dict | None

dict | None: Task list of the workflow instance or None if the request fails.

Example dict | None
dict | None

{ 'links': { 'data': {...} }, 'results': { 'draftprocess_id': 157555, 'workflow_type': '1_1'} }

dict | None

}

Source code in pyxecm/otcs.py
def create_draft_process(self, workflow_id, documents: list) -> dict | None:
    """Initiate a draft process. This is the first step to start a process (workflow instance)

    Args:
        workflow_id (int): Node ID of the workflow maps
        documents (list): node IDs of the attachmewnt documents

    Returns:
        dict | None: Task list of the workflow instance or None if the request fails.

        Example:
        {
            'links': {
                'data': {...}
            },
            'results': {
                'draftprocess_id': 157555,
                'workflow_type': '1_1'}
            }
        }
    """

    draft_process_body_post_data = {
        "workflow_id": workflow_id,
        "doc_ids": documents,
        #            "AttachDocuments": True, # THIS DOES NOT WORK!!!
    }

    request_url = self.config()["draftProcessUrl"]
    request_header = self.request_form_header()

    logger.debug(
        "Create a draft process for workflow with ID -> %s and body -> %s; calling -> %s",
        str(workflow_id),
        str(draft_process_body_post_data),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data={"body": json.dumps(draft_process_body_post_data)},
        timeout=None,
        failure_message="Failed to create draft process from workflow with ID -> {}".format(
            workflow_id
        ),
    )

create_item(parent_id, item_type, item_name, item_description='', url='', original_id=0, show_error=True)

Create an Extended ECM item. This REST call is somewhat limited. It cannot set featured item or hidden item. It does also not accept owner group information.

Parameters:

Name Type Description Default
parent_id int

Node ID of the parent

required
item_type str

Type of the item (e.g. 0 = folder, 140 = URL)

required
item_name str

Name of the item

required
item_description str

Description of the item

''
url str

Address of the URL item (if it is an URL item type)

''
original_id int

Node ID of the original (referenced) item. Required if a shortcut item is created

0
show_error bool

Log an error if item cration fails. Otherwise log a warning.

True

Returns: dict: Request response of the create item call or None if the REST call has failed.

Source code in pyxecm/otcs.py
def create_item(
    self,
    parent_id: int,
    item_type: str,
    item_name: str,
    item_description: str = "",
    url: str = "",
    original_id: int = 0,
    show_error: bool = True,
) -> dict | None:
    """Create an Extended ECM item. This REST call is somewhat limited. It cannot set featured item or hidden item.
       It does also not accept owner group information.

    Args:
        parent_id (int): Node ID of the parent
        item_type (str): Type of the item (e.g. 0 = folder, 140 = URL)
        item_name (str): Name of the item
        item_description (str, optional): Description of the item
        url (str, optional): Address of the URL item (if it is an URL item type)
        original_id (int, optional): Node ID of the original (referenced) item.
                                     Required if a shortcut item is created
        show_error (bool, optional): Log an error if item cration fails. Otherwise log a warning.
    Returns:
        dict: Request response of the create item call or None if the REST call has failed.
    """

    create_item_post_data = {
        "parent_id": parent_id,
        "type": item_type,
        "name": item_name,
        "description": item_description,
    }

    if url:
        create_item_post_data["url"] = url
    if original_id > 0:
        create_item_post_data["original_id"] = original_id

    request_url = self.config()["nodesUrlv2"]
    request_header = self.request_form_header()

    logger.debug(
        "Create item -> '%s' (type -> %s) under parent with ID -> %s; calling -> %s",
        item_name,
        item_type,
        str(parent_id),
        request_url,
    )

    # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data={"body": json.dumps(create_item_post_data)},
        timeout=None,
        warning_message="Cannot create item -> '{}'".format(item_name),
        failure_message="Failed to create item -> '{}'".format(item_name),
        show_error=show_error,
    )

create_records_management_hold(hold_type, name, comment, alternate_id='', parent_id=0, date_applied='', date_to_remove='')

Create a new Records Management Hold.

Parameters:

Name Type Description Default
hold_type str

type of the Hold

required
name str

name of the RSI

required
comment str

comment

required
alternate_id str

alternate hold ID

''
parent_id int

ID of the parent node. If parent_id is 0 the item will be created right under "Hold Management" (top level item)

0
date_applied str

create date of the Hold in this format: YYYY-MM-DDTHH:mm:ss

''
date_to_remove str

suspend date of the Hold in this format: YYYY-MM-DDTHH:mm:ss

''

Returns: dict: Hold data or None if the request fails. The dict structure is this: {'holdID': }

Source code in pyxecm/otcs.py
def create_records_management_hold(
    self,
    hold_type: str,
    name: str,
    comment: str,
    alternate_id: str = "",
    parent_id: int = 0,
    date_applied: str = "",
    date_to_remove: str = "",
) -> dict | None:
    """Create a new Records Management Hold.

    Args:
        hold_type (str): type of the Hold
        name (str): name of the RSI
        comment (str): comment
        alternate_id (str, optional): alternate hold ID
        parent_id (int, optional): ID of the parent node. If parent_id is 0 the item will be created right under "Hold Management" (top level item)
        date_applied (str, optional): create date of the Hold in this format: YYYY-MM-DDTHH:mm:ss
        date_to_remove (str, optional): suspend date of the Hold in this format: YYYY-MM-DDTHH:mm:ss
    Returns:
        dict: Hold data or None if the request fails. The dict structure is this: {'holdID': <ID>}
    """

    if date_applied == "":
        now = datetime.now()
        date_applied = now.strftime("%Y-%m-%dT%H:%M:%S")

    create_hold_post_data = {
        "type": hold_type,
        "name": name,
        "comment": comment,
        "date_applied": date_applied,
        "date_to_remove": date_to_remove,
        "alternate_id": alternate_id,
    }

    if parent_id > 0:
        create_hold_post_data["parent_id"] = parent_id

    request_url = self.config()["holdsUrl"]

    request_header = self.request_form_header()

    logger.debug(
        "Create Records Management Hold -> %s; calling -> %s", name, request_url
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=create_hold_post_data,
        timeout=None,
        failure_message="Failed to create Records Management Hold -> '{}'".format(
            name
        ),
    )

create_records_management_rsi(name, status, status_date, description, subject, title, dispcontrol)

Create a new Records Management RSI.

Parameters:

Name Type Description Default
name str

name of the RSI

required
status str

status of the RSI

required
status_date str

statusDate of the RSI YYYY-MM-DDTHH:mm:ss

required
description str

description of the RSI

required
subject str

status of the RSI

required
title str

status of the RSI

required
dispcontrol bool

status of the RSI

required

Returns: dict: RSI data or None if the request fails.

Source code in pyxecm/otcs.py
def create_records_management_rsi(
    self,
    name: str,
    status: str,
    status_date: str,
    description: str,
    subject: str,
    title: str,
    dispcontrol: bool,
) -> dict | None:
    """Create a new Records Management RSI.

    Args:
        name (str): name of the RSI
        status (str): status of the RSI
        status_date (str): statusDate of the RSI YYYY-MM-DDTHH:mm:ss
        description (str): description of the RSI
        subject (str): status of the RSI
        title (str): status of the RSI
        dispcontrol (bool): status of the RSI
    Returns:
        dict: RSI data or None if the request fails.
    """

    if status_date == "":
        now = datetime.now()
        status_date = now.strftime("%Y-%m-%dT%H:%M:%S")

    create_rsi_post_data = {
        "name": name,
        "status": status,
        "statusDate": status_date,
        "description": description,
        "subject": subject,
        "title": title,
        "dispcontrol": dispcontrol,
    }

    request_url = self.config()["rsiSchedulesUrl"]

    request_header = self.request_form_header()

    logger.debug(
        "Create Records Management RSI -> %s; calling -> %s", name, request_url
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=create_rsi_post_data,
        timeout=None,
        failure_message="Failed to create Records Management RSI -> '{}'".format(
            name
        ),
    )

create_records_management_rsi_schedule(rsi_id, stage, event_type=1, object_type='LIV', rule_code='', rule_comment='', date_to_use=91, retention_years=0, retention_months=0, retention_days=0, category_id=0, attribute_id=0, year_end_month=12, year_end_day=31, retention_intervals=1, fixed_retention=True, maximum_retention=True, fixed_date='', event_condition='', disposition='', action_code=0, description='', new_status='', min_num_versions_to_keep=1, purge_superseded=False, purge_majors=False, mark_official_rendition=False)

Create a new Records Management RSI Schedule for an existing RSI.

Parameters:

Name Type Description Default
rsi_id int

ID of an existing RSI the schedule should be created for

required
stage str

retention stage - this is the key parameter to define multiple stages (stages are basically schedules)

required
event_type int

1 Calculated Date, 2 Calendar Calculation, 3 Event Based, 4 Fixed Date, 5 Permanent

1
object_type str

either "LIV" - Classified Objects (default) or "LRM" - RM Classifications

'LIV'
rule_code str

rule code - this value must be defined upfront

''
rule_comment str

comment for the rule

''
date_to_use int

91 Create Date, 92 Reserved Data, 93 Modification Date, 94 Status Date, 95 Records Date

91
retention_years int

years to wait before disposition

0
retention_months int

month to wait before disposition

0
retention_days int

days to wait before disposition

0
category_id int

ID of the category

0
attribute_id int

ID of the category attribute

0
year_end_month int

month the year ends (default = 12)

12
year_end_day int

day the year ends (default = 31)

31
retention_intervals int

retention intervals

1
fixed_retention bool

fixedRetention

True
maximum_retention (bool, optional)

maximumRetention

True
fixed_date(str, optional

fixed date format : YYYY-MM-DDTHH:mm:ss

required
event_condition str

eventCondition

''
disposition str

disposition

''
action_code int

0 None, 1 Change Status, 7 Close, 8 Finalize Record, 9 Mark Official, 10 Export, 11 Update Storage Provider, 12 Delete Electronic Format, 15 Purge Versions, 16 Make Rendition, 32 Destroy

0
description str

description

''
new_status str

new status

''
min_num_versions_to_keep int

minimum document versions to keep, . Default is 1.

1
purge_superseded bool

purge superseded. Default is False.

False
purge_majors bool

purge majors. Default is False.

False
mark_official_rendition bool

mark official rendition. Default is False.

False

Returns: dict: RSI Schedule data or None if the request fails.

Source code in pyxecm/otcs.py
def create_records_management_rsi_schedule(
    self,
    rsi_id: int,
    stage: str,
    event_type: int = 1,
    object_type: str = "LIV",
    rule_code: str = "",
    rule_comment: str = "",
    date_to_use: int = 91,
    retention_years: int = 0,
    retention_months: int = 0,
    retention_days: int = 0,
    category_id: int = 0,
    attribute_id: int = 0,
    year_end_month: int = 12,
    year_end_day: int = 31,
    retention_intervals: int = 1,
    fixed_retention: bool = True,
    maximum_retention: bool = True,
    fixed_date: str = "",
    event_condition: str = "",
    disposition: str = "",
    action_code: int = 0,
    description: str = "",
    new_status: str = "",
    min_num_versions_to_keep: int = 1,
    purge_superseded: bool = False,
    purge_majors: bool = False,
    mark_official_rendition: bool = False,
) -> dict | None:
    """Create a new Records Management RSI Schedule for an existing RSI.

    Args:
        rsi_id (int): ID of an existing RSI the schedule should be created for
        stage (str): retention stage - this is the key parameter to define multiple stages (stages are basically schedules)
        event_type (int): 1 Calculated Date, 2 Calendar Calculation, 3 Event Based, 4 Fixed Date, 5 Permanent
        object_type (str): either "LIV" - Classified Objects (default) or "LRM" - RM Classifications
        rule_code (str, optional): rule code - this value must be defined upfront
        rule_comment (str, optional): comment for the rule
        date_to_use (int, optional): 91 Create Date, 92 Reserved Data, 93 Modification Date, 94 Status Date, 95 Records Date
        retention_years (int, optional): years to wait before disposition
        retention_months (int, optional): month to wait before disposition
        retention_days (int, optional): days to wait before disposition
        category_id (int, optional): ID of the category
        attribute_id (int, optional): ID of the category attribute
        year_end_month (int, optional): month the year ends (default = 12)
        year_end_day (int, optional): day the year ends (default = 31)
        retention_intervals (int, optional): retention intervals
        fixed_retention (bool, optional): fixedRetention
        maximum_retention (bool,optional): maximumRetention
        fixed_date(str, optional): fixed date format : YYYY-MM-DDTHH:mm:ss
        event_condition (str, optional): eventCondition
        disposition (str, optional): disposition
        action_code (int, optional): 0 None, 1 Change Status, 7 Close, 8 Finalize Record, 9 Mark Official, 10 Export, 11 Update Storage Provider, 12 Delete Electronic Format, 15 Purge Versions, 16 Make Rendition, 32 Destroy
        description (str, optional): description
        new_status (str, optional): new status
        min_num_versions_to_keep (int, optional): minimum document versions to keep, . Default is 1.
        purge_superseded (bool, optional): purge superseded. Default is False.
        purge_majors (bool, optional): purge majors. Default is False.
        mark_official_rendition (bool, optional): mark official rendition. Default is False.
    Returns:
        dict: RSI Schedule data or None if the request fails.
    """

    if fixedDate == "":
        now = datetime.now()
        fixedDate = now.strftime("%Y-%m-%dT%H:%M:%S")

    create_rsi_schedule_post_data = {
        "objectType": object_type,
        "stage": stage,
        "eventType": event_type,
        "ruleCode": rule_code,
        "ruleComment": rule_comment,
        "dateToUse": date_to_use,
        "retentionYears": retention_years,
        "retentionMonths": retention_months,
        "retentionDays": retention_days,
        "categoryId": category_id,
        "attributeId": attribute_id,
        "yearEndMonth": year_end_month,
        "yearEndDay": year_end_day,
        "retentionIntervals": retention_intervals,
        "fixedRetention": fixed_retention,
        "maximumRetention": maximum_retention,
        "fixedDate": fixed_date,
        "eventCondition": event_condition,
        "disposition": disposition,
        "actionCode": action_code,
        "description": description,
        "newStatus": new_status,
        "minNumVersionsToKeep": min_num_versions_to_keep,
        "purgeSuperseded": purge_superseded,
        "purgeMajors": purge_majors,
        "markOfficialRendition": mark_official_rendition,
    }

    request_url = self.config()["rsiSchedulesUrl"] + "/" + str(rsi_id) + "/stages"

    request_header = self.request_form_header()

    logger.debug(
        "Create Records Management RSI Schedule -> %s for RSI -> %s; calling -> %s",
        stage,
        str(rsi_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=create_rsi_schedule_post_data,
        timeout=None,
        failure_message="Failed to create Records Management RSI Schedule -> '{}' for RSI -> {}".format(
            stage, rsi_id
        ),
    )

create_transport_workbench(workbench_name)

Create a Workbench in the Transport Volume.

Parameters:

Name Type Description Default
workbench_name str

Name of the workbench to be created

required

Returns: dict: Create response or None if the creation fails.

Source code in pyxecm/otcs.py
def create_transport_workbench(self, workbench_name: str) -> dict | None:
    """Create a Workbench in the Transport Volume.

    Args:
        workbench_name (str): Name of the workbench to be created
    Returns:
        dict: Create response or None if the creation fails.
    """

    create_worbench_post_data = {"type": "528", "name": workbench_name}

    request_url = self.config()["nodesUrlv2"]
    request_header = self.request_form_header()

    logger.debug(
        "Create transport workbench -> %s; calling -> %s",
        workbench_name,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=create_worbench_post_data,
        timeout=None,
        failure_message="Failed to create transport workbench -> {}".format(
            workbench_name
        ),
    )

create_wiki(parent_id, name, description='', show_error=True)

Create an Extended ECM Wiki.

Parameters:

Name Type Description Default
parent_id int

Node ID of the parent

required
name str

Name of the wiki item

required
description str

Description of the wiki item

''
show_error bool

Log an error if item cration fails. Otherwise log a warning.

True

Returns: dict: Request response of the create item call or None if the REST call has failed.

Source code in pyxecm/otcs.py
def create_wiki(
    self,
    parent_id: int,
    name: str,
    description: str = "",
    show_error: bool = True,
) -> dict | None:
    """Create an Extended ECM Wiki.

    Args:
        parent_id (int): Node ID of the parent
        name (str): Name of the wiki item
        description (str, optional): Description of the wiki item
        show_error (bool, optional): Log an error if item cration fails. Otherwise log a warning.
    Returns:
        dict: Request response of the create item call or None if the REST call has failed.
    """

    create_wiki_post_data = {
        "parent_id": parent_id,
        "type": 5573,
        "name": name,
        "description": description,
    }

    request_url = self.config()["nodesUrlv2"]
    request_header = self.request_form_header()

    logger.debug(
        "Create wiki -> '%s' under parent with ID -> %s; calling -> %s",
        name,
        str(parent_id),
        request_url,
    )

    # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data={"body": json.dumps(create_wiki_post_data)},
        timeout=None,
        warning_message="Cannot create wiki -> '{}'".format(name),
        failure_message="Failed to create wiki -> '{}'".format(name),
        show_error=show_error,
    )

create_wiki_page(wiki_id, name, content='', description='', show_error=True)

Create an Extended ECM wiki page.

Parameters:

Name Type Description Default
wiki_id int

Node ID of the wiki

required
name str

Name of the wiki page

required
content str

Content of the page (typically HTML)

''
show_error bool

Log an error if item cration fails. Otherwise log a warning.

True

Returns: dict: Request response of the create wiki page call or None if the REST call has failed.

Source code in pyxecm/otcs.py
def create_wiki_page(
    self,
    wiki_id: int,
    name: str,
    content: str = "",
    description: str = "",
    show_error: bool = True,
) -> dict | None:
    """Create an Extended ECM wiki page.

    Args:
        wiki_id (int): Node ID of the wiki
        name (str): Name of the wiki page
        content (str, optional): Content of the page (typically HTML)
        show_error (bool, optional): Log an error if item cration fails. Otherwise log a warning.
    Returns:
        dict: Request response of the create wiki page call or None if the REST call has failed.
    """

    create_wiki_page_post_data = {
        "parent_id": wiki_id,
        "type": 5574,
        "name": name,
        "description": description,
        "TextField": content,
    }

    request_url = self.config()["nodesUrl"]
    # Header needs to just include the cookie:
    request_header = self.cookie()

    logger.debug(
        "Create wiki page -> '%s' in wiki with ID -> %s; calling -> %s",
        name,
        str(wiki_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=create_wiki_page_post_data,
        timeout=None,
        warning_message="Cannot create wiki page -> '{}'".format(name),
        failure_message="Failed to create wiki page -> '{}'".format(name),
        show_error=show_error,
    )

create_workspace(workspace_template_id, workspace_name, workspace_description, workspace_type, category_data=None, external_system_id=None, bo_type=None, bo_id=None, parent_id=None, ibo_workspace_id=None, external_modify_date=None, external_create_date=None, show_error=True)

Create a new business workspace.

Parameters:

Name Type Description Default
workspace_template_id int

ID of the workspace template

required
workspace_name str

Name of the workspace

required
workspace_description str

Description of the workspace

required
workspace_type int

Type ID of the workspace

required
category_data dict

Category and attributes

None
external_system_id str

Identifier of the external system (None if no external system)

None
bo_type str

Business object type (None if no external system)

None
bo_id str

Business object identifier / key (None if no external system)

None
parent_id str

Parent ID of the workspaces. Needs only be specified in special cases where workspace location cannot be derived from workspace type definition or if it is a sub-workspace.

None
ibo_workspace_id int

Node ID of an existing workspace that is already connected to another external system. This allows for subsequent calls to coonect the workspace to multiple Business Objects (IBO = Identical Business Objects)

None
show_error bool

Log an error if workspace cration fails. Otherwise log a warning.

True

Returns: dict: Workspace Create Form data or None if the request fails.

Source code in pyxecm/otcs.py
def create_workspace(
    self,
    workspace_template_id: int,
    workspace_name: str,
    workspace_description: str,
    workspace_type: int,
    category_data: dict | None = None,
    external_system_id: str | None = None,
    bo_type: str | None = None,
    bo_id: str | None = None,
    parent_id: int | None = None,
    ibo_workspace_id: int | None = None,
    external_modify_date: str | None = None,
    external_create_date: str | None = None,
    show_error: bool = True,
) -> dict | None:
    """Create a new business workspace.

    Args:
        workspace_template_id (int): ID of the workspace template
        workspace_name (str): Name of the workspace
        workspace_description (str): Description of the workspace
        workspace_type (int): Type ID of the workspace
        category_data (dict): Category and attributes
        external_system_id (str, optional): Identifier of the external system (None if no external system)
        bo_type (str, optional): Business object type (None if no external system)
        bo_id (str, optional): Business object identifier / key (None if no external system)
        parent_id (str, optional): Parent ID of the workspaces. Needs only be specified in special
                                   cases where workspace location cannot be derived from workspace
                                   type definition or if it is a sub-workspace.
        ibo_workspace_id (int, optional): Node ID of an existing workspace that is already connected to another
                                          external system. This allows for subsequent calls to coonect the workspace
                                          to multiple Business Objects (IBO = Identical Business Objects)
        external_create_date (str, optional) value of the source system in format 2024-06-24
        external_modify_date (str, optional) value of the source system in format 2024-06-24
        show_error (bool, optional): Log an error if workspace cration fails. Otherwise log a warning.
    Returns:
        dict: Workspace Create Form data or None if the request fails.
    """

    # Avoid linter warning W0102
    if category_data is None:
        category_data = {}

    create_workspace_post_data = {
        "template_id": str(workspace_template_id),
        "name": workspace_name,
        "description": workspace_description,
        "wksp_type_id": str(workspace_type),
        "type": str(848),
        "roles": category_data,
        "external_create_date": external_create_date,
        "external_modify_date": external_modify_date,
    }

    # Is this workspace connected to a business application / external system?
    if external_system_id and bo_type and bo_id:
        create_workspace_post_data["ext_system_id"] = external_system_id
        create_workspace_post_data["bo_type"] = bo_type
        create_workspace_post_data["bo_id"] = bo_id
        logger.debug(
            "Use business object connection -> (%s, %s, %s) for workspace -> '%s'",
            external_system_id,
            bo_type,
            bo_id,
            workspace_name,
        )
        if ibo_workspace_id:
            logger.debug(
                "This is a subsequent call to create a cross-application workspace (IBO)"
            )
            create_workspace_post_data["ibo_workspace_id"] = ibo_workspace_id

    # If workspace creation location cannot be derived from the workspace type
    # there may be an optional parent parameter passed to this method. This can
    # also be the case if workspaces are nested into each other:
    if parent_id is not None:
        create_workspace_post_data["parent_id"] = parent_id
        logger.debug(
            "Use specified location -> %s for workspace -> '%s'",
            str(parent_id),
            workspace_name,
        )
    else:
        logger.debug(
            "Determine location of workspace -> '%s' via workspace type -> '%s'",
            workspace_name,
            str(workspace_type),
        )

    request_url = self.config()["businessWorkspacesUrl"]
    request_header = self.request_form_header()

    logger.debug(
        "Create workspace -> '%s' with type -> '%s' from template -> %s; calling -> %s",
        workspace_name,
        str(workspace_type),
        str(workspace_template_id),
        request_url,
    )

    # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
    # See https://developer.opentext.com/apis/14ba85a7-4693-48d3-8c93-9214c663edd2/4403207c-40f1-476a-b794-fdb563e37e1f/07229613-7ef4-4519-8b8a-47eaff639d42#operation/createBusinessWorkspace
    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data={"body": json.dumps(create_workspace_post_data)},
        timeout=None,
        warning_message="Failed to create workspace -> '{}' from template with ID -> {}".format(
            workspace_name, workspace_template_id
        ),
        failure_message="Failed to create workspace -> '{}' from template with ID -> {}".format(
            workspace_name, workspace_template_id
        ),
        show_error=show_error,
    )

create_workspace_relationship(workspace_id, related_workspace_id, relationship_type='child', show_error=True)

Create a relationship between two workspaces.

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace

required
related_workspace_id int

ID of the related workspace

required
relationship_type str

"parent" or "child" - "child" is default if omitted

'child'
show_error bool

Log an error if relationship cration fails. Otherwise log a warning.

True

Returns: dict: Workspace Relationship data (json) or None if the request fails.

Source code in pyxecm/otcs.py
def create_workspace_relationship(
    self,
    workspace_id: int,
    related_workspace_id: int,
    relationship_type: str = "child",
    show_error: bool = True,
) -> dict | None:
    """Create a relationship between two workspaces.

    Args:
        workspace_id (int): ID of the workspace
        related_workspace_id (int): ID of the related workspace
        relationship_type (str, optional): "parent" or "child" - "child" is default if omitted
        show_error (bool, optional): Log an error if relationship cration fails.
                                     Otherwise log a warning.
    Returns:
        dict: Workspace Relationship data (json) or None if the request fails.
    """

    create_workspace_relationship_post_data = {
        "rel_bw_id": str(related_workspace_id),
        "rel_type": relationship_type,
    }

    request_url = self.config()[
        "businessWorkspacesUrl"
    ] + "/{}/relateditems".format(workspace_id)
    request_header = self.request_form_header()

    logger.debug(
        "Create workspace relationship between -> %s and -> %s; calling -> %s",
        str(workspace_id),
        str(related_workspace_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=create_workspace_relationship_post_data,
        timeout=None,
        warning_message="Cannot create workspace relationship between -> {} and -> {}. It may already exist.".format(
            workspace_id, related_workspace_id
        ),
        failure_message="Failed to create workspace relationship between -> {} and -> {}".format(
            workspace_id, related_workspace_id
        ),
        show_error=show_error,
    )

credentials()

Get credentials (username + password)

Returns:

Name Type Description
dict dict

dictionary with username and password

Source code in pyxecm/otcs.py
def credentials(self) -> dict:
    """Get credentials (username + password)

    Returns:
        dict: dictionary with username and password
    """
    return {
        "username": self.config()["username"],
        "password": self.config()["password"],
    }

cs_public_url()

Returns the public (external) Extended ECM URL (incl. base_path /cs/cs )

Returns:

Name Type Description
str str

Extended ECM Public URL

Source code in pyxecm/otcs.py
def cs_public_url(self) -> str:
    """Returns the public (external) Extended ECM URL (incl. base_path /cs/cs )

    Returns:
        str: Extended ECM Public URL
    """
    return self.config()["csPublicUrl"]

cs_support_public_url()

Returns the Extended ECM Public Support URL

Returns:

Name Type Description
str str

Extended ECM Public Support URL

Source code in pyxecm/otcs.py
def cs_support_public_url(self) -> str:
    """Returns the Extended ECM Public Support URL

    Returns:
        str: Extended ECM Public Support URL
    """
    return self.config()["supportPublicUrl"]

cs_support_url()

Returns the Extended ECM Support URL

Returns:

Name Type Description
str str

Extended ECM Support URL

Source code in pyxecm/otcs.py
def cs_support_url(self) -> str:
    """Returns the Extended ECM Support URL

    Returns:
        str: Extended ECM Support URL
    """
    return self.config()["supportUrl"]

cs_url()

Returns the Extended ECM URL

Returns:

Name Type Description
str str

Extended ECM URL

Source code in pyxecm/otcs.py
def cs_url(self) -> str:
    """Returns the Extended ECM URL

    Returns:
        str: Extended ECM URL
    """
    return self.config()["csUrl"]

date_is_newer(date_old, date_new) classmethod

Compare two dates, typically create or modification dates

Parameters:

Name Type Description Default
date_old str

the date that is considered older

required
date_new str

the date that is considered newer

required

Returns:

Name Type Description
bool bool

True if date_new is indeed newer as date_old, False otherwise

Source code in pyxecm/otcs.py
@classmethod
def date_is_newer(cls, date_old: str, date_new: str) -> bool:
    """Compare two dates, typically create or modification dates

    Args:
        date_old (str): the date that is considered older
        date_new (str): the date that is considered newer

    Returns:
        bool: True if date_new is indeed newer as date_old, False otherwise
    """

    if not date_old or not date_new:
        return True

    # Define the date formats
    format1 = "%Y-%m-%dT%H:%M:%SZ"  # Format: "YYYY-MM-DDTHH:MM:SSZ"
    format2 = "%Y-%m-%d %H:%M:%S"  # Format: "YYY-MM-DD HH:MM:SS"
    format3 = "%Y-%m-%dT%H:%M:%S"  # Format: "YYY-MM-DD HH:MM:SS"
    format4 = "%Y-%m-%d"  # Format: "YYY-MM-DD"

    # Parse the dates
    try:
        if "T" in date_old and "Z" in date_old:
            old_date = datetime.strptime(date_old, format1)
        elif " " in date_old:
            old_date = datetime.strptime(date_old, format2)
        elif "T" in date_old:
            old_date = datetime.strptime(date_old, format3)
        else:
            old_date = datetime.strptime(date_old, format4)
    except ValueError:
        return True

    try:
        if "T" in date_new and "Z" in date_new:
            new_date = datetime.strptime(date_new, format1)
        elif " " in date_new:
            new_date = datetime.strptime(date_new, format2)
        elif "T" in date_new:
            new_date = datetime.strptime(date_new, format3)
        else:
            new_date = datetime.strptime(date_new, format4)
    except ValueError:
        return True

    # Compare the dates
    return new_date > old_date

delete_node(node_id, purge=False)

Delete an existing node

Parameters:

Name Type Description Default
node_id int

ID of the node to be deleted

required
purge bool

If True, immediately purge the item from the recycle bin

False

Returns:

Name Type Description
dict dict | None

response of the REST call; None in case of a failure

Source code in pyxecm/otcs.py
def delete_node(self, node_id: int, purge: bool = False) -> dict | None:
    """Delete an existing node

    Args:
        node_id (int): ID of the node to be deleted
        purge (bool, optional): If True, immediately purge the item from the recycle bin

    Returns:
        dict: response of the REST call; None in case of a failure
    """

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id)
    request_header = self.request_form_header()

    logger.debug(
        "Delete node with ID -> %s%s; calling -> %s",
        str(node_id),
        " (with immediate purging from recycle bin)" if purge else "",
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="DELETE",
        headers=request_header,
        timeout=None,
        failure_message="Failed to delete node with ID -> {}".format(node_id),
    )

    # Do we want to immediately purge it from the Recycle Bin?
    if response and purge:
        self.purge_node(node_id)

    return response

deploy_transport(package_url, package_name, package_description='', replacements=None, extractions=None)

Main method to deploy a transport. This uses subfunctions to upload, unpackage and deploy the transport, and creates the required workbench.

Parameters:

Name Type Description Default
package_url str

URL to download the transport package.

required
package_name str

Name of the transport package ZIP file

required
package_description str

Description of the transport package

''
replacements list of dicts

List of replacement values to be applied to all XML files in transport; each dict needs to have two values: - placeholder: text to replace - value: text to replace with

None
extractions list of dicts

List of XML Subtrees to extract each XML file in transport; each dict needs to have two values: - xpath: defining the subtree to extract - enabled: True if the extraction is active

None

Returns: dict: Deploy response or None if the deployment fails.

Source code in pyxecm/otcs.py
def deploy_transport(
    self,
    package_url: str,
    package_name: str,
    package_description: str = "",
    replacements: list | None = None,
    extractions: list | None = None,
) -> dict | None:
    """Main method to deploy a transport. This uses subfunctions to upload,
       unpackage and deploy the transport, and creates the required workbench.

    Args:
        package_url (str): URL to download the transport package.
        package_name (str): Name of the transport package ZIP file
        package_description (str): Description of the transport package
        replacements (list of dicts): List of replacement values to be applied
                                      to all XML files in transport;
                                      each dict needs to have two values:
                                      - placeholder: text to replace
                                      - value: text to replace with
        extractions (list of dicts): List of XML Subtrees to extract
                                     each XML file in transport;
                                     each dict needs to have two values:
                                      - xpath: defining the subtree to extract
                                      - enabled: True if the extraction is active
    Returns:
        dict: Deploy response or None if the deployment fails.
    """

    if replacements is None:
        replacements = []
    if extractions is None:
        extractions = []

    # Preparation: get volume IDs for Transport Warehouse (root volume and Transport Packages)
    response = self.get_volume(525)
    transport_root_volume_id = self.get_result_value(response, "id")
    if not transport_root_volume_id:
        logger.error("Failed to retrieve transport root volume")
        return None
    logger.debug("Transport root volume ID -> %s", str(transport_root_volume_id))

    response = self.get_node_by_parent_and_name(
        transport_root_volume_id, "Transport Packages"
    )
    transport_package_volume_id = self.get_result_value(response, "id")
    if not transport_package_volume_id:
        logger.error("Failed to retrieve transport package volume")
        return None
    logger.debug(
        "Transport package volume ID -> %s", str(transport_package_volume_id)
    )

    # Step 1: Upload Transport Package
    logger.debug(
        "Check if transport package -> '%s' already exists...", package_name
    )
    response = self.get_node_by_parent_and_name(
        transport_package_volume_id, package_name
    )
    package_id = self.get_result_value(response, "id")
    if package_id:
        logger.debug(
            "Transport package -> '%s' does already exist; existing package ID -> %s",
            package_name,
            str(package_id),
        )
    else:
        logger.debug(
            "Transport package -> '%s' does not yet exist, loading from -> %s",
            package_name,
            package_url,
        )
        # If we have string replacements configured execute them now:
        if replacements:
            logger.debug(
                "Transport -> '%s' has replacements -> %s",
                package_name,
                str(replacements),
            )
            self.replace_transport_placeholders(package_url, replacements)
        else:
            logger.debug("Transport -> '%s' has no replacements!", package_name)
        # If we have data extractions configured execute them now:
        if extractions:
            logger.debug(
                "Transport -> '%s' has extractions -> %s",
                package_name,
                str(extractions),
            )
            self.extract_transport_data(package_url, extractions)
        else:
            logger.debug("Transport -> '%s' has no extractions!", package_name)
        # Upload package to Extended ECM:
        response = self.upload_file_to_volume(
            package_url, package_name, "application/zip", 531
        )
        package_id = self.get_result_value(response, "id")
        if not package_id:
            logger.error("Failed to upload transport package -> %s", package_url)
            return None
        logger.debug(
            "Successfully uploaded transport package -> '%s'; new package ID -> %s",
            package_name,
            str(package_id),
        )

    # Step 2: Create Transport Workbench (if not yet exist)
    workbench_name = package_name.split(".")[0]
    logger.debug(
        "Check if workbench -> '%s' is already deployed...", workbench_name
    )
    # check if the package name has the suffix "(deployed)" - this indicates it is alreadey
    # successfully deployed (see renaming at the end of this method)
    response = self.get_node_by_parent_and_name(
        transport_root_volume_id, workbench_name + " (deployed)"
    )
    workbench_id = self.get_result_value(response, "id")
    if workbench_id:
        logger.debug(
            "Workbench -> '%s' has already been deployed successfully; existing workbench ID -> %s; skipping transport",
            workbench_name,
            str(workbench_id),
        )
        # we return and skip this transport...
        return response
    else:
        logger.debug("Check if workbench -> '%s' already exists...", workbench_name)
        response = self.get_node_by_parent_and_name(
            transport_root_volume_id, workbench_name
        )
        workbench_id = self.get_result_value(response, "id")
        if workbench_id:
            logger.debug(
                "Workbench -> '%s' does already exist but is not successfully deployed; existing workbench ID -> %s",
                workbench_name,
                str(workbench_id),
            )
        else:
            response = self.create_transport_workbench(workbench_name)
            workbench_id = self.get_result_value(response, "id")
            if not workbench_id:
                logger.error("Failed to create workbench -> '%s'", workbench_name)
                return None
            logger.debug(
                "Successfully created workbench -> '%s'; new workbench ID -> %s",
                workbench_name,
                str(workbench_id),
            )

    # Step 3: Unpack Transport Package to Workbench
    logger.debug(
        "Unpack transport package -> '%s' (%s) to workbench -> '%s' (%s)",
        package_name,
        str(package_id),
        workbench_name,
        str(workbench_id),
    )
    response = self.unpack_transport_package(package_id, workbench_id)
    if not response:
        logger.error("Failed to unpack the transport package -> '%s'", package_name)
        return None
    logger.debug(
        "Successfully unpackaged to workbench -> '%s' (%s)",
        workbench_name,
        str(workbench_id),
    )

    # Step 4: Deploy Workbench
    logger.debug("Deploy workbench -> '%s' (%s)", workbench_name, str(workbench_id))
    response = self.deploy_workbench(workbench_id)
    if not response:
        logger.error("Failed to deploy workbench -> '%s'", workbench_name)
        return None

    logger.debug(
        "Successfully deployed workbench -> '%s' (%s)",
        workbench_name,
        str(workbench_id),
    )
    self.rename_node(
        workbench_id,
        workbench_name + " (deployed)",
        package_description,
    )

    return response

deploy_workbench(workbench_id)

Deploy an existing Workbench.

Parameters:

Name Type Description Default
workbench_d int

ID of the workbench to be deployed

required

Returns: dict: Deploy response or None if the deployment fails.

Source code in pyxecm/otcs.py
def deploy_workbench(self, workbench_id: int) -> dict | None:
    """Deploy an existing Workbench.

    Args:
        workbench_d (int): ID of the workbench to be deployed
    Returns:
        dict: Deploy response or None if the deployment fails.
    """

    request_url = self.config()["nodesUrlv2"] + "/" + str(workbench_id) + "/deploy"
    request_header = self.request_form_header()

    logger.debug(
        "Deploy workbench with ID -> %s; calling -> %s",
        str(workbench_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        timeout=None,
        failure_message="Failed to deploy workbench with ID -> {}".format(
            workbench_id
        ),
    )

do_request(url, method='GET', headers=None, data=None, json_data=None, files=None, timeout=REQUEST_TIMEOUT, show_error=True, show_warning=False, warning_message='', failure_message='', success_message='', max_retries=REQUEST_MAX_RETRIES, retry_forever=False, parse_request_response=True)

Call an Extended ECM REST API in a safe way

Parameters:

Name Type Description Default
url str

URL to send the request to.

required
method str

HTTP method (GET, POST, etc.). Defaults to "GET".

'GET'
headers dict | None

Request Headers. Defaults to None.

None
data dict | None

Request payload. Defaults to None

None
files dict | None

Dictionary of {"name": file-tuple} for multipart encoding upload. file-tuple can be a 2-tuple ("filename", fileobj) or a 3-tuple ("filename", fileobj, "content_type")

None
timeout int | None

Timeout for the request in seconds. Defaults to REQUEST_TIMEOUT.

REQUEST_TIMEOUT
show_error bool

Whether or not an error should be logged in case of a failed REST call. If False, then only a warning is logged. Defaults to True.

True
warning_message str

Specific warning message. Defaults to "". If not given the error_message will be used.

''
failure_message str

Specific error message. Defaults to "".

''
success_message str

Specific success message. Defaults to "".

''
max_retries int

How many retries on Connection errors? Default is REQUEST_MAX_RETRIES.

REQUEST_MAX_RETRIES
retry_forever bool

Eventually wait forever - without timeout. Defaults to False.

False
parse_request_response bool

should the response.text be interpreted as json and loaded into a dictionary. True is the default.

True

Returns:

Type Description
dict | None

dict | None: Response of Extended ECM REST API or None in case of an error.

Source code in pyxecm/otcs.py
def do_request(
    self,
    url: str,
    method: str = "GET",
    headers: dict | None = None,
    data: dict | None = None,
    json_data: dict | None = None,
    files: dict | None = None,
    timeout: int | None = REQUEST_TIMEOUT,
    show_error: bool = True,
    show_warning: bool = False,
    warning_message: str = "",
    failure_message: str = "",
    success_message: str = "",
    max_retries: int = REQUEST_MAX_RETRIES,
    retry_forever: bool = False,
    parse_request_response: bool = True,
) -> dict | None:
    """Call an Extended ECM REST API in a safe way

    Args:
        url (str): URL to send the request to.
        method (str, optional): HTTP method (GET, POST, etc.). Defaults to "GET".
        headers (dict | None, optional): Request Headers. Defaults to None.
        data (dict | None, optional): Request payload. Defaults to None
        files (dict | None, optional): Dictionary of {"name": file-tuple} for multipart encoding upload.
                                       file-tuple can be a 2-tuple ("filename", fileobj) or a 3-tuple ("filename", fileobj, "content_type")
        timeout (int | None, optional): Timeout for the request in seconds. Defaults to REQUEST_TIMEOUT.
        show_error (bool, optional): Whether or not an error should be logged in case of a failed REST call.
                                     If False, then only a warning is logged. Defaults to True.
        warning_message (str, optional): Specific warning message. Defaults to "". If not given the error_message will be used.
        failure_message (str, optional): Specific error message. Defaults to "".
        success_message (str, optional): Specific success message. Defaults to "".
        max_retries (int, optional): How many retries on Connection errors? Default is REQUEST_MAX_RETRIES.
        retry_forever (bool, optional): Eventually wait forever - without timeout. Defaults to False.
        parse_request_response (bool, optional): should the response.text be interpreted as json and loaded into a dictionary. True is the default.

    Returns:
        dict | None: Response of Extended ECM REST API or None in case of an error.
    """

    # In case of an expired session we reauthenticate and
    # try 1 more time. Session expiration should not happen
    # twice in a row:
    retries = 0

    while True:
        try:
            # We protect this with a lock to not read
            # a cookie that is in process of being renewed
            # by another thread:
            with self._session_lock:
                request_cookie = self.cookie()
            response = requests.request(
                method=method,
                url=url,
                data=data,
                json=json_data,
                files=files,
                headers=headers,
                cookies=request_cookie,
                timeout=timeout,
            )

            if response.ok:
                if success_message:
                    logger.info(success_message)
                if parse_request_response:
                    return self.parse_request_response(response)
                else:
                    return response
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                # Try to reauthenticate:
                self.reauthenticate(request_cookie=request_cookie, thread_safe=True)
                retries += 1
                logger.debug("Reauthentication complete. Retry = %s", str(retries))
                logger.debug(
                    "Old cookie -> %s, new cookie -> %s",
                    str(request_cookie),
                    str(self.cookie()),
                )
            elif response.status_code == 500 and "already exists" in response.text:
                logger.warning(
                    (
                        warning_message
                        + " (it already exists); details -> {}".format(
                            response.text
                        )
                        if warning_message
                        else failure_message
                        + " (it already exists); details -> {}".format(
                            response.text
                        )
                    ),
                )
                if parse_request_response:
                    return self.parse_request_response(response)
                else:
                    return response
            else:
                # Handle plain HTML responses to not pollute the logs
                content_type = response.headers.get("content-type", None)
                if content_type == "text/html":
                    response_text = "HTML content (only printed in debug log)"
                else:
                    response_text = response.text

                if show_error:
                    logger.error(
                        "%s; status -> %s/%s; error -> %s",
                        failure_message,
                        response.status_code,
                        HTTPStatus(response.status_code).phrase,
                        response_text,
                    )
                elif show_warning:
                    logger.warning(
                        "%s; status -> %s/%s; warning -> %s",
                        warning_message if warning_message else failure_message,
                        response.status_code,
                        HTTPStatus(response.status_code).phrase,
                        response_text,
                    )

                if content_type == "text/html":
                    logger.debug(
                        "%s; status -> %s/%s; debug output -> %s",
                        failure_message,
                        response.status_code,
                        HTTPStatus(response.status_code).phrase,
                        response.text,
                    )

                return None
        except requests.exceptions.Timeout:
            if retries <= max_retries:
                logger.warning(
                    "Request timed out. Retrying in %s seconds...",
                    str(REQUEST_RETRY_DELAY),
                )
                retries += 1
                time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
            else:
                logger.error(
                    "%s; timeout error",
                    failure_message,
                )
                if retry_forever:
                    # If it fails after REQUEST_MAX_RETRIES retries we let it wait forever
                    logger.warning("Turn timeouts off and wait forever...")
                    timeout = None
                else:
                    return None
        except requests.exceptions.ConnectionError:
            if retries <= max_retries:
                logger.warning(
                    "Connection error. Retrying in %s seconds...",
                    str(REQUEST_RETRY_DELAY),
                )
                retries += 1
                time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
            else:
                logger.error(
                    "%s; connection error",
                    failure_message,
                )
                if retry_forever:
                    # If it fails after REQUEST_MAX_RETRIES retries we let it wait forever
                    logger.warning("Turn timeouts off and wait forever...")
                    timeout = None
                    time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
                else:
                    return None
        # end try
        logger.debug(
            "Retrying REST API %s call -> %s... (retry = %s, cookie -> %s)",
            method,
            url,
            str(retries),
            str(self.cookie()),
        )

download_config_file(otcs_url_suffix, file_path, search='', replace='')

Download a config file from a given OTCS URL. This is NOT for downloading documents from within the OTCS repository but for configuration files such as app packages for MS Teams.

Parameters:

Name Type Description Default
otcs_url_suffix str

OTCS URL suffix starting typically starting with /cs/cs?func=, e.g. /cs/cs?func=officegroups.DownloadTeamsPackage

required
file_path str

local path to save the file (direcotry + filename)

required
search str

optional string to search for a replacement

''
replace str

optional replacement

''

Returns: bool: True if the download succeeds, False otherwise

Source code in pyxecm/otcs.py
def download_config_file(
    self, otcs_url_suffix: str, file_path: str, search: str = "", replace: str = ""
) -> bool:
    """Download a config file from a given OTCS URL. This is NOT
        for downloading documents from within the OTCS repository
        but for configuration files such as app packages for MS Teams.

    Args:
        otcs_url_suffix (str): OTCS URL suffix starting typically starting
                                  with /cs/cs?func=,
                                  e.g. /cs/cs?func=officegroups.DownloadTeamsPackage
        file_path (str): local path to save the file (direcotry + filename)
        search (str, optional): optional string to search for a replacement
        replace (str, optional): optional replacement
    Returns:
        bool: True if the download succeeds, False otherwise
    """

    request_url = self.config()["baseUrl"] + otcs_url_suffix
    request_header = self.request_download_header()

    logger.debug("Download config file from URL -> %s", request_url)

    try:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=REQUEST_TIMEOUT,
        )
        response.raise_for_status()
    except requests.exceptions.HTTPError as errh:
        logger.error("Http Error -> %s", errh.strerror)
        return False
    except requests.exceptions.ConnectionError as errc:
        logger.error("Error Connecting -> %s", errc.strerror)
        return False
    except requests.exceptions.Timeout as errt:
        logger.error("Timeout Error -> %s", errt.strerror)
        return False
    except requests.exceptions.RequestException as err:
        logger.error("Request error -> %s", err.strerror)
        return False

    content = response.content

    if search:
        logger.debug(
            "Search for all occurances of '%s' in the config file and replace them with '%s'",
            search,
            replace,
        )
        content = content.replace(search.encode("utf-8"), replace.encode("utf-8"))

    # Open file in write binary mode
    with open(file=file_path, mode="wb") as file:
        # Write the content to the file
        file.write(content)

    logger.debug(
        "Successfully downloaded config file -> %s to -> '%s'; status code -> %s",
        request_url,
        file_path,
        response.status_code,
    )

    return True

download_document(node_id, file_path, version_number='')

Download a document from Extended ECM to local file system.

Parameters:

Name Type Description Default
node_id int

node ID of the document to download

required
file_path str

local file path (directory)

required
version_number str

version of the document to download. If version = "" then download the latest version.

''

Returns: bool: True if the document has been download to the specified file. False otherwise.

Source code in pyxecm/otcs.py
def download_document(
    self, node_id: int, file_path: str, version_number: str = ""
) -> bool:
    """Download a document from Extended ECM to local file system.

    Args:
        node_id (int): node ID of the document to download
        file_path (str): local file path (directory)
        version_number (str): version of the document to download.
                                 If version = "" then download the latest
                                 version.
    Returns:
        bool: True if the document has been download to the specified file.
                 False otherwise.
    """

    if not version_number:
        response = self.get_latest_document_version(node_id)
        if not response:
            logger.error(
                "Cannot get latest version of document with ID -> %s", str(node_id)
            )
            return False
        version_number = response["data"]["version_number"]

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "/versions/"
        + str(version_number)
        + "/content"
    )
    request_header = self.request_download_header()

    logger.debug(
        "Download document with node ID -> %s; calling -> %s",
        str(node_id),
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to download document with node ID -> {}".format(
            node_id
        ),
        parse_request_response=False,
    )

    if response is None:
        return False

    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        logger.warning("Directory -> '%s' does not exist, creating it.", directory)
        os.makedirs(directory)

    try:
        with open(file_path, "wb") as file:
            file.write(response.content)
    except Exception as exc:
        logger.error("Error while writing file content -> %s", exc)
        return False

    return True

download_document_multi_threading(node_id, file_path)

Multi-threading variant of download_document()

Parameters:

Name Type Description Default
node_id int

Node ID of the document to download

required
file_path str

file system path - location to download to

required
Source code in pyxecm/otcs.py
def download_document_multi_threading(self, node_id: int, file_path: str):
    """Multi-threading variant of download_document()

    Args:
        node_id (int): Node ID of the document to download
        file_path (str): file system path - location to download to
    """

    # Aquire and Release Thread limit to limit parallel executions

    with self._semaphore:
        self.download_document(node_id=node_id, file_path=file_path)

exist_result_item(response, key, value, property_name='properties')

Check existence of key / value pair in the response properties of an Extended ECM REST API call.

Parameters:

Name Type Description Default
response dict

REST response from an OTCS REST Call

required
key str

property name (key)

required
value str

value to find in the item with the matching key

required
property_name str

name of the substructure that includes the values

'properties'

Returns: bool: True if the value was found, False otherwise

Source code in pyxecm/otcs.py
def exist_result_item(
    self, response: dict, key: str, value: str, property_name: str = "properties"
) -> bool:
    """Check existence of key / value pair in the response properties of an Extended ECM REST API call.

    Args:
        response (dict): REST response from an OTCS REST Call
        key (str): property name (key)
        value (str): value to find in the item with the matching key
        property_name (str, optional): name of the substructure that includes the values
    Returns:
        bool: True if the value was found, False otherwise
    """

    if not response:
        return False
    if not "results" in response:
        return False

    results = response["results"]
    # check if results is a list or a dict (both is possible - dependent on the actual REST API):
    if isinstance(results, dict):
        # result is a dict - we don't need index value:
        if not "data" in results:
            return False
        data = results["data"]
        if isinstance(data, dict):
            # data is a dict - we don't need index value:
            if property_name and not property_name in data:
                logger.error(
                    "There's no dictionary -> '%s' in data -> %s",
                    property_name,
                    data,
                )
                return False
            properties = data[property_name]
            if isinstance(properties, dict):
                if key in properties:
                    return properties[key] == value
                else:
                    return False
            elif isinstance(properties, list):
                # properties is a list we iterate through the list and try to find the key:
                for item in properties:
                    if key in item and item[key] == value:
                        return True
            else:
                logger.error(
                    "Properties needs to be a list or dict but it is -> %s",
                    str(type(properties)),
                )
                return False
        elif isinstance(data, list):
            # data is a list
            for item in data:
                if property_name and not property_name in item:
                    logger.error(
                        "There's no dictionary -> '%s' in the data list item -> %s",
                        property_name,
                        item,
                    )
                    continue
                # if properties if passed as empty string then we assume that
                # the key fields are directly in the item dictionary. This is
                # the case e.g. with the V2 Proxy APIs
                if not property_name:
                    properties = item
                else:
                    properties = item[property_name]
                if key in properties and properties[key] == value:
                    return True
            return False
        else:
            logger.error(
                "Data needs to be a list or dict but it is -> %s", str(type(data))
            )
            return False
    elif isinstance(results, list):
        # result is a list - we need index value
        for result in results:
            if not "data" in result:
                continue
            data = result["data"]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                properties = data[property_name]
                if key in properties and properties[key] == value:
                    return True
            elif isinstance(data, list):
                # data is a list we iterate through the list and try to find the key:
                for item in data:
                    properties = item[property_name]
                    if key in properties and properties[key] == value:
                        return True
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s",
                    str(type(data)),
                )
                return False
        return False
    else:
        logger.error(
            "Result needs to be a list or dict but it is -> %s", str(type(results))
        )
        return False

extract_transport_data(zip_file_path, extractions)

Search and extract XML data from the transport package

Parameters:

Name Type Description Default
zip_file_path str

Path to transport zip file

required
extractions list of dicts

List of extraction values; dict needs to have two values: * xpath: structure to find * enabed (optional): if the extraction is active

required

Returns: True if successful, False otherwise. THIS METHOD MODIFIES EXTRACTIONS BY ADDING A NEW KEY "data" TO EACH EXTRACTION ELEMENT!!

Source code in pyxecm/otcs.py
def extract_transport_data(self, zip_file_path: str, extractions: list) -> bool:
    """Search and extract XML data from the transport package

    Args:
        zip_file_path (str): Path to transport zip file
        extractions (list of dicts): List of extraction values; dict needs to have two values:
                                     * xpath: structure to find
                                     * enabed (optional): if the extraction is active
    Returns:
        True if successful, False otherwise. THIS METHOD MODIFIES EXTRACTIONS
        BY ADDING A NEW KEY "data" TO EACH EXTRACTION ELEMENT!!
    """

    if not os.path.isfile(zip_file_path):
        logger.error("Zip file -> '%s' not found.", zip_file_path)
        return False

    # Extract the zip file to a temporary directory
    zip_file_folder = os.path.splitext(zip_file_path)[0]
    with zipfile.ZipFile(zip_file_path, "r") as zfile:
        zfile.extractall(zip_file_folder)

    # Extract data from all XML files in the directory and its subdirectories
    for extraction in extractions:
        if not "xpath" in extraction:
            logger.error(
                "Extraction needs an XPath but it is not specified. Skipping..."
            )
            continue
        if "enabled" in extraction and not extraction["enabled"]:
            logger.debug(
                "Extraction for transport -> '%s' is disabled. Skipping...",
                zip_file_path,
            )
            continue

        xpath = extraction["xpath"]
        logger.debug(
            "Using xpath -> %s to extract the data",
            xpath,
        )

        # This delivers a list of strings containing the extracted data:
        extracted_data = XML.extract_from_xml_files(
            zip_file_folder,
            xpath,
        )
        if extracted_data:
            logger.debug(
                "Extraction with XPath -> %s has been successfully completed for Transport package -> %s",
                xpath,
                zip_file_folder,
            )
            # Add the extracted elements to the extraction data structure (dict).
            extraction["data"] = extracted_data
        else:
            logger.warning(
                "Extraction with XPath -> %s has not delivered any data for Transport package -> %s",
                xpath,
                zip_file_folder,
            )
            extraction["data"] = []

    # Return the path to the new zip file
    return True

feme_embedd_metadata(node_id, node_type=144, crawl=False, wait_for_completion=True, message_override={}, timeout=10.0)

RUN FEME metadata embedding on provided node for Aviator

Parameters:

Name Type Description Default
node_id int

Node ID

required
node_type int

Subtype of the node. Defaults to 144.

144
crawl bool

description. Defaults to False.

False
wait_for_completion bool

description. Defaults to True.

True
message_override dict

description. Defaults to {}.

{}
timout float

Time in seconds to wait until the WebSocket times out. Defaults to 10.0

required
Source code in pyxecm/otcs.py
def feme_embedd_metadata(
    self,
    node_id: int,
    node_type: int = 144,
    crawl: bool = False,
    wait_for_completion: bool = True,
    message_override: dict = {},
    timeout: float = 10.0,
):
    """RUN FEME metadata embedding on provided node for Aviator

    Args:
        node_id (int): Node ID
        node_type (int, optional): Subtype of the node. Defaults to 144.
        crawl (bool, optional): _description_. Defaults to False.
        wait_for_completion (bool, optional): _description_. Defaults to True.
        message_override (dict, optional): _description_. Defaults to {}.
        timout (float): Time in seconds to wait until the WebSocket times out. Defaults to 10.0
    """

    async def _inner(
        uri: str,
        node_id: int,
        node_type: int,
        crawl: bool,
        wait_for_completion: bool,
        message_override: dict,
        timeout: float,
    ):

        logger.debug("Open WebSocket connection to %s", uri)
        async with websockets.connect(uri) as websocket:

            # define it one node, or all childs should be processed
            task = ("crawl" if crawl else "index",)
            finished = "crawled" if crawl else "uploaded"

            message = {
                "task": task,
                "nodes": [{"id": node_id, "type": node_type}],
                "documents": False,
                "workspaces": True,
                "images": False,
                "binaries": False,
                "upload": True,
                "remove": False,
                "imagePrompt": "Extract all information from the picture, please.",
                "maxRelations": 0,
            }
            message.update(message_override)
            logger.debug("Sending message via WebSocket -> %s", message)
            await websocket.send(json.dumps(message))

            # Continuously listen for messages
            while wait_for_completion:
                response = await asyncio.wait_for(
                    websocket.recv(), timeout=timeout
                )  # await websocket.recv()  # Receive response

                logger.debug("Received message via WebSocket -> %s", response)
                response = json.loads(response)

                if response.get("name", None) == finished:  # crawled
                    logger.info(
                        "Received completed message via WebSocket, close connection"
                    )
                    break

    event_loop = asyncio.new_event_loop()
    asyncio.set_event_loop(event_loop)

    uri = self._config["feme_uri"]
    task = _inner(
        uri=uri,
        node_id=node_id,
        node_type=node_type,
        crawl=crawl,
        wait_for_completion=wait_for_completion,
        message_override=message_override,
        timeout=timeout,
    )

    try:
        event_loop.run_until_complete(task)
    except websockets.exceptions.ConnectionClosed as exc:  # :
        logger.error("WebSocket connection was closed: %s", exc)

    except TimeoutError:
        logger.error(
            "Error during Feme WebSocket connection: TimeoutError, WebSocket did not receive a message in time (%ss)",
            timeout,
        )

    except Exception as exc:
        logger.error("Error during Feme WebSocket connection: %s", exc)

    event_loop.close()

get_business_object_type(external_system_id, type_name, expand_workspace_type=True, expand_external_system=True)

Get business object type information. Unfortunately this REST API is pretty much limited. It does not return Field names of external system properties and also does not return property groups defined.

Parameters:

Name Type Description Default
external_system_id str

External system Id (such as "TM6")

required
type_name str

Type name of the business object (such as "SAP Customer")

required

Returns: dict: Business Object Type information or None if the request fails.

Example response:
{
    'businessProperties': [
        {
            'attributeID': '14012_29',
            'categoryID': '14012',
            'name': 'Name',
            'type': 'String'
        },
        {
            'attributeID': '14012_28',
            'categoryID': '14012',
            'name': 'Customer Number',
            'type': 'String'
        }
    ]
    'bwsinfo': {'id': None},
    'cadxref_doc_info': {'has_relation': False},
    'categories': [],
    'claimed_doc_info': {'is_claimed': False},
    'columns': [{...}, {...}, {...}, {...}],
    'doctemplates_info': {'isInDocTemplateVolTree': False},
    'followups': [],
    'nicknames': {'nickname': '16568'},
    'properties': {
        'advanced_versioning': None,
        'container': False,
        'container_size': 0,
        'create_date': '2017-11-23T16:43:34Z',
        'create_user_id': 1000,
        'description': '',
        'description_multilingual': {...},
        'external_create_date': None,
        'external_identity': '',
        ...
    },
    'rmiconsdata': {'class_id': 0, 'official': 0, 'show_classify': False, 'show_hold': False, 'show_hold_tab': False, 'show_label_tab': True, 'show_official': False, 'show_xref': False, 'show_xref_tab': False},
    'sestatus_doc_info': {'is_se_document': False, 'sync_tooltip': ''},
    'sharing_info': {'is_shared': False, 'sync_state': -1},
    'showmainruleicon': False,
    ...
}
Source code in pyxecm/otcs.py
def get_business_object_type(
    self,
    external_system_id: str,
    type_name: str,
    expand_workspace_type: bool = True,
    expand_external_system: bool = True,
) -> dict | None:
    """Get business object type information. Unfortunately this REST API is
       pretty much limited. It does not return Field names of external system properties
       and also does not return property groups defined.

    Args:
        external_system_id (str): External system Id (such as "TM6")
        type_name (str): Type name of the business object (such as "SAP Customer")
    Returns:
        dict: Business Object Type information or None if the request fails.

        Example response:
        {
            'businessProperties': [
                {
                    'attributeID': '14012_29',
                    'categoryID': '14012',
                    'name': 'Name',
                    'type': 'String'
                },
                {
                    'attributeID': '14012_28',
                    'categoryID': '14012',
                    'name': 'Customer Number',
                    'type': 'String'
                }
            ]
            'bwsinfo': {'id': None},
            'cadxref_doc_info': {'has_relation': False},
            'categories': [],
            'claimed_doc_info': {'is_claimed': False},
            'columns': [{...}, {...}, {...}, {...}],
            'doctemplates_info': {'isInDocTemplateVolTree': False},
            'followups': [],
            'nicknames': {'nickname': '16568'},
            'properties': {
                'advanced_versioning': None,
                'container': False,
                'container_size': 0,
                'create_date': '2017-11-23T16:43:34Z',
                'create_user_id': 1000,
                'description': '',
                'description_multilingual': {...},
                'external_create_date': None,
                'external_identity': '',
                ...
            },
            'rmiconsdata': {'class_id': 0, 'official': 0, 'show_classify': False, 'show_hold': False, 'show_hold_tab': False, 'show_label_tab': True, 'show_official': False, 'show_xref': False, 'show_xref_tab': False},
            'sestatus_doc_info': {'is_se_document': False, 'sync_tooltip': ''},
            'sharing_info': {'is_shared': False, 'sync_state': -1},
            'showmainruleicon': False,
            ...
        }
    """

    query = {
        "expand_ext_system": expand_external_system,
        "expand_wksp_type": expand_workspace_type,
    }

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    encoded_type_name = type_name.replace("/", "%2F")

    request_url = (
        self.config()["externalSystemUrl"]
        + "/"
        + external_system_id
        + "/botypes/"
        + encoded_type_name
        + "?{}".format(encoded_query)
    )
    request_header = self.request_form_header()

    logger.debug(
        "Get business object type -> '%s' for external system -> %s; calling -> %s",
        type_name,
        external_system_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get business object type -> '{}' for external system -> {}".format(
            type_name, external_system_id
        ),
    )

get_business_object_types()

Get information for all configured business object types.

Returns: dict: Workspace Types information (for all external systems) or None if the request fails.

Source code in pyxecm/otcs.py
def get_business_object_types(self) -> dict | None:
    """Get information for all configured business object types.

    Args:
        None
    Returns:
        dict: Workspace Types information (for all external systems)
              or None if the request fails.
    """

    request_url = self.config()["businessObjectTypesUrl"]
    request_header = self.request_form_header()

    logger.debug(
        "Get all business object types; calling -> %s",
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get business object types",
    )

get_business_objects(external_system_id, type_name, where_clauses=None, limit=None, page=None)

Get all business objects for an external system and a given business object type.

Parameters:

Name Type Description Default
external_system_id str

External system Id (such as "TM6")

required
type_name str

Type name of the business object (such as "SAP Customer")

required
where_clause dict

filter the results based on 1 or kultiple where clauses (THE NAME CONVENTION FOR THE FIELDS IS UNCLEAR)

required
limit int

maximum result items

None
page int

page for chunked result lists

None

Returns: dict: Business Object information (for all results) or None if the request fails.

Example response (for a Salesforce Account):
{
    'links': {'data': {...}},
    'paging': {'limit': 500, 'page': 1, 'page_total': 1, 'range_max': 15, 'range_min': 1, 'total_count': 15},
    'results': {
        'column_descriptions': [
            {
                'fieldLabel': 'AccountDetail.AccountID',
                'fieldName': 'Account.ID',
                'keyField': 'X',
                'length': 18,
                'position': 4
            },
            {
                'fieldLabel': 'AccountName',
                'fieldName': 'Account.Name',
                'keyField': ' ',
                'length': 255,
                'position': 2
            },
            {
                'fieldLabel': 'AccountNumber',
                'fieldName': 'Account.AccountNumber',
                'keyField': ' ',
                'length': 40,
                'position': 3
            },
            ...
        ]
        'max_rows_exceeded': False,
        'result_rows': [
            {
                'AccountDetail.AccountID': '001Dn00000w0bCQIAY',
                'AccountDetail.AccountName': 'Jet Stream Inc.',
                'AccountDetail.AccountNumber': '1234567',
                'AccountDetail.AccountOwner': 'Nick Wheeler',
                'AccountDetail.AnnualRevenue': '$900001',
                'AccountDetail.Description': '',
                'AccountDetail.Employees': '',
                'AccountDetail.Industry': 'Biotechnology',
                'AccountDetail.ParentAccount': '',
                ...
            },
            ...
        ]
    }
}
Source code in pyxecm/otcs.py
def get_business_objects(
    self,
    external_system_id: str,
    type_name: str,
    where_clauses: dict | None = None,
    limit: int | None = None,
    page: int | None = None,
) -> dict | None:
    """Get all business objects for an external system and a given business object type.

    Args:
        external_system_id (str): External system Id (such as "TM6")
        type_name (str): Type name of the business object (such as "SAP Customer")
        where_clause (dict, optional): filter the results based on 1 or kultiple
                                       where clauses (THE  NAME CONVENTION FOR THE
                                       FIELDS IS UNCLEAR)
        limit (int, optional): maximum result items
        page (int, optional): page for chunked result lists
    Returns:
        dict: Business Object information (for all results)
              or None if the request fails.

        Example response (for a Salesforce Account):
        {
            'links': {'data': {...}},
            'paging': {'limit': 500, 'page': 1, 'page_total': 1, 'range_max': 15, 'range_min': 1, 'total_count': 15},
            'results': {
                'column_descriptions': [
                    {
                        'fieldLabel': 'AccountDetail.AccountID',
                        'fieldName': 'Account.ID',
                        'keyField': 'X',
                        'length': 18,
                        'position': 4
                    },
                    {
                        'fieldLabel': 'AccountName',
                        'fieldName': 'Account.Name',
                        'keyField': ' ',
                        'length': 255,
                        'position': 2
                    },
                    {
                        'fieldLabel': 'AccountNumber',
                        'fieldName': 'Account.AccountNumber',
                        'keyField': ' ',
                        'length': 40,
                        'position': 3
                    },
                    ...
                ]
                'max_rows_exceeded': False,
                'result_rows': [
                    {
                        'AccountDetail.AccountID': '001Dn00000w0bCQIAY',
                        'AccountDetail.AccountName': 'Jet Stream Inc.',
                        'AccountDetail.AccountNumber': '1234567',
                        'AccountDetail.AccountOwner': 'Nick Wheeler',
                        'AccountDetail.AnnualRevenue': '$900001',
                        'AccountDetail.Description': '',
                        'AccountDetail.Employees': '',
                        'AccountDetail.Industry': 'Biotechnology',
                        'AccountDetail.ParentAccount': '',
                        ...
                    },
                    ...
                ]
            }
        }
    """

    query = {
        "ext_system_id": external_system_id,
        "bo_type": type_name,
    }
    if limit:
        query["limit"] = limit
    if page:
        query["page"] = page
    if where_clauses:
        query.update(
            {("where_" + key): value for key, value in where_clauses.items()}
        )

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = self.config()["businessObjectsUrl"] + "?{}".format(encoded_query)
    request_header = self.request_form_header()

    logger.debug(
        "Get all business objects of type -> '%s' from external system -> %s; calling -> %s",
        type_name,
        external_system_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get business objects of type -> '{}' from external system -> {}".format(
            type_name, external_system_id
        ),
    )

Get business object type information. Unfortunately this REST API is pretty much limited. It does not return Field names of external system properties and also does not return property groups defined.

Parameters:

Name Type Description Default
external_system_id str

External system Id (such as "TM6")

required
type_name str

Type name of the business object (such as "SAP Customer")

required

Returns: dict: Business Object Search Form or None if the request fails.

Source code in pyxecm/otcs.py
def get_business_objects_search(
    self,
    external_system_id: str,
    type_name: str,
) -> dict | None:
    """Get business object type information. Unfortunately this REST API is
       pretty much limited. It does not return Field names of external system properties
       and also does not return property groups defined.

    Args:
        external_system_id (str): External system Id (such as "TM6")
        type_name (str): Type name of the business object (such as "SAP Customer")
    Returns:
        dict: Business Object Search Form or None if the request fails.
    """

    query = {
        "ext_system_id": external_system_id,
        "bo_type": type_name,
    }

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = self.config()["businessObjectsSearchUrl"] + "?{}".format(
        encoded_query
    )
    request_header = self.request_form_header()

    logger.debug(
        "Get search form for business object type -> '%s' and external system -> %s; calling -> %s",
        type_name,
        external_system_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get search form for business object type -> '{}' and external system -> {}".format(
            type_name, external_system_id
        ),
    )

get_category_value(node_id, category_id, attribute_id, set_id=None, set_row=1)

Lookup the value of an attribute if category ID, set ID and attribute ID are known. If you only have the names use get_category_value_by_name()

Parameters:

Name Type Description Default
node_id int

Node ID the category is assigned to

required
category_id int

ID of the category

required
attribute_id int

ID of the attribute (the pure ID without underscores)

required
set_id int

ID of the set. Defaults to None.

None
set_row int

Index of the row (first row = 1!). Defaults to 1.

1

Returns:

Type Description
str | list | None

str | list | None: The value of the attribute. If it is a multi-value attribute a list will be returned.

Source code in pyxecm/otcs.py
def get_category_value(
    self,
    node_id: int,
    category_id: int,
    attribute_id: int,
    set_id: int | None = None,
    set_row: int = 1,
) -> str | list | None:
    """Lookup the value of an attribute if category ID, set ID and attribute ID
       are known. If you only have the names use get_category_value_by_name()

    Args:
        node_id (int): Node ID the category is assigned to
        category_id (int): ID of the category
        attribute_id (int): ID of the attribute (the pure ID without underscores)
        set_id (int, optional): ID of the set. Defaults to None.
        set_row (int, optional): Index of the row (first row = 1!). Defaults to 1.

    Returns:
        str | list | None: The value of the attribute. If it is a multi-value attribute a list will be returned.
    """

    if set_id and set_row:
        att_id = (
            str(category_id)
            + "_"
            + str(set_id)
            + "_"
            + str(set_row)
            + "_"
            + str(attribute_id)
        )
    elif set_id:
        att_id = str(category_id) + "_" + str(set_id) + "_" + str(attribute_id)
    else:
        att_id = str(category_id) + "_" + str(attribute_id)

    response = self.get_node_categories(node_id=node_id, metadata=False)
    categories = response["results"]

    value = None

    for category in categories:
        if att_id in category["data"]["categories"]:
            value = category["data"]["categories"][att_id]
            break

    return value

get_category_value_by_name(node_id, category_name, attribute_name, set_name=None, set_row=1)

Lookup the value of an attribute if category name, set name and attribute name are known.

Parameters:

Name Type Description Default
node_id int

ID of the node the category is assigned to.

required
category_name str

Name of the category.

required
attribute_name str

Name of the attribute.

required
set_name str | None

Name of the set. Defaults to None.

None
set_row int

Index of the row (first row = 1!). Defaults to 1.

1

Returns:

Type Description
str | list | None

str | list | None: The value of the attribute. If it is a multi-value attribute a list will be returned.

Source code in pyxecm/otcs.py
def get_category_value_by_name(
    self,
    node_id: int,
    category_name: str,
    attribute_name: str,
    set_name: str | None = None,
    set_row: int = 1,
) -> str | list | None:
    """Lookup the value of an attribute if category name, set name and attribute name
       are known.

    Args:
        node_id (int): ID of the node the category is assigned to.
        category_name (str): Name of the category.
        attribute_name (str): Name of the attribute.
        set_name (str | None, optional): Name of the set. Defaults to None.
        set_row (int, optional): Index of the row (first row = 1!). Defaults to 1.

    Returns:
        str | list | None: The value of the attribute. If it is a multi-value attribute a list will be returned.
    """

    (_, cat_definitions) = self.get_node_category_definition(node_id, category_name)
    if not cat_definitions:
        logger.warning("No categories are assigned to node -> %s", str(node_id))
        return None

    if set_name:
        lookup = set_name + ":" + attribute_name
    else:
        lookup = attribute_name

    if not lookup in cat_definitions:
        logger.error("Cannot find attribute -> '%s' in category -> '%s'")

    att_def = cat_definitions[lookup]
    att_id = att_def["id"]
    if "_x_" in att_id:
        att_id = att_id.replace("_x_", "_" + str(set_row) + "_")

    value = None

    response = self.get_node_categories(node_id=node_id, metadata=False)
    categories = response["results"]
    for category in categories:
        if att_id in category["data"]["categories"]:
            value = category["data"]["categories"][att_id]
            break

    return value

get_data()

Get the Data object that holds all loaded Content Server items (see method load_items())

Returns:

Name Type Description
Data Data

Datastructure with all processed articles.

Source code in pyxecm/otcs.py
def get_data(self) -> Data:
    """Get the Data object that holds all loaded Content Server items (see method load_items())

    Returns:
        Data: Datastructure with all processed articles.
    """

    return self._data

get_document_content(node_id, version_number='', parse_request_response=False)

Get document content from Extended ECM.

Parameters:

Name Type Description Default
node_id int

node ID of the document to download

required
version_number str

version of the document to download. If version = "" then download the latest version.

''

Returns: bytes | dict | None: content of the file or None in case of an error. If parse_request_response is True then then the content is interpreted as JSON and delivered as a dictionary

Source code in pyxecm/otcs.py
def get_document_content(
    self,
    node_id: int,
    version_number: str = "",
    parse_request_response: bool = False,
) -> bytes | dict | None:
    """Get document content from Extended ECM.

    Args:
        node_id (int): node ID of the document to download
        version_number (str, optional): version of the document to download.
                                        If version = "" then download the latest
                                        version.
    Returns:
        bytes | dict | None: content of the file or None in case of an error.
                             If parse_request_response is True then then the
                             content is interpreted as JSON and delivered as a dictionary
    """

    if not version_number:
        response = self.get_latest_document_version(node_id)
        if not response:
            logger.error(
                "Cannot get latest version of document with ID -> %s", str(node_id)
            )
        version_number = response["data"]["version_number"]

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "/versions/"
        + str(version_number)
        + "/content"
    )
    request_header = self.request_download_header()

    logger.debug(
        "Get document with node ID -> %s and version -> %s; calling -> %s",
        str(node_id),
        str(version_number),
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to download document with node ID -> {}".format(
            node_id
        ),
        parse_request_response=parse_request_response,
    )

    if parse_request_response:
        # In this case response.content has been interpreted as JSON
        # and delivered as a Python dict (or None in case of an error):
        return response

    if response is not None:
        # In sthis case the unparsed content is delivered as bytes:
        return response.content

    return None

get_document_templates(parent_id)

Get all document templates for a given target location.

Parameters:

Name Type Description Default
parent_id int

node ID of target location (e.g. a folder)

required

Returns:

Name Type Description
dict

response of the REST call (converted to a Python dictionary)

Example response:

'results': [ { 'container': False, 'hasTemplates': False, 'name': 'Document', 'subtype': 144, 'templates': [ { 'description_multilingual': {...}, 'id': 16817, 'isDPWizardAvailable': False, 'mime_type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'name': 'Innovate Procurement Contract Template 2022.docx', 'name_multilingual': {...}, 'size': 144365, 'sizeformatted': '141 KB', 'type': 144 }, { ... } ] }

]

Source code in pyxecm/otcs.py
def get_document_templates(self, parent_id: int):
    """Get all document templates for a given target location.

    Args:
        parent_id (int): node ID of target location (e.g. a folder)

    Returns:
        dict: response of the REST call (converted to a Python dictionary)

        Example response:
        'results': [
            {
                'container': False,
                'hasTemplates': False,
                'name': 'Document',
                'subtype': 144,
                'templates': [
                    {
                        'description_multilingual': {...},
                        'id': 16817,
                        'isDPWizardAvailable': False,
                        'mime_type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                        'name': 'Innovate Procurement Contract Template 2022.docx',
                        'name_multilingual': {...},
                        'size': 144365,
                        'sizeformatted': '141 KB',
                        'type': 144
                    },
                    {
                        ...
                    }
                ]
            }
        ]
    """

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(parent_id)
        + "/doctemplates?subtypes={144}&sidepanel_subtypes={144}"
    )
    request_header = self.request_form_header()

    logger.debug(
        "Get document templates for target location -> %s (parent ID); calling -> %s",
        str(parent_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get document templates for parent folder with ID -> {}".format(
            parent_id
        ),
    )

get_document_workflows(node_id, parent_id)

Get a list of available workflows for a document ID and a parent ID.

Parameters:

Name Type Description Default
node_id int

node ID of the document

required
parent_id int

node ID of the parent

required

Returns:

Name Type Description
list list

list of available workflows

Example list
list

{ 'links': { 'data': {...} }, 'results': { 'data': [ { 'DataID': 25397, 'Name': 'Contract Approval Workflow', 'WorkflowType': 100 }, { 'DataID': 25442, 'Name': 'Contract Approval Workflow (2 steps)', 'WorkflowType': 100 }, ... ], 'fError': '', 'fErrorDetail': '', 'statusMsg': None} }

list

}

Source code in pyxecm/otcs.py
def get_document_workflows(self, node_id: int, parent_id: int) -> list:
    """Get a list of available workflows for a document ID and a parent ID.

    Args:
        node_id (int): node ID of the document
        parent_id (int): node ID of the parent

    Returns:
        list: list of available workflows

        Example:
        {
            'links': {
                'data': {...}
            },
            'results': {
                'data': [
                    {
                        'DataID': 25397,
                        'Name': 'Contract Approval Workflow',
                        'WorkflowType': 100
                    },
                    {
                        'DataID': 25442,
                        'Name': 'Contract Approval Workflow (2 steps)',
                        'WorkflowType': 100
                    },
                    ...
                ],
                'fError': '',
                'fErrorDetail': '',
                'statusMsg': None}
            }
        }
    """

    request_url = self.config()[
        "docWorkflowUrl"
    ] + "?doc_id={}&parent_id={}".format(node_id, parent_id)
    request_header = self.request_form_header()

    logger.debug(
        "Get workflows for node ID -> %s and parent ID -> %s; calling -> %s",
        str(node_id),
        str(parent_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get workflows for node ID -> {} and parent ID -> {}".format(
            node_id, parent_id
        ),
    )

get_draft_process(draftprocess_id)

Get draft process data.

    Args:
        draftprocess_id (int): ID of an existing draft process

    Returns:
        dict | None: Get the details for a draft process.
                     Delivers None in case of an error.

        Example result:
        {
            'data': {
                'actions': [
                    {
                        'key': 'Initiate',
                        'label': 'Start'
                    }
                ],
                'attachment_centric_default_mode': 'properties',
                'attachments_on': True,
                'authentication': False,
                'comments_on': True,
                'data_packages': [...],
                'enableTopAlignedLabel': True,
                'instructions': 'Please pick the Approver (type-ahead search)

', 'process_id': 158037, 'task': {...}, 'title': 'Contract Approval Workflow (1 step)', 'workflow_type': '1_1' }, 'forms': [ {...} ] }

Source code in pyxecm/otcs.py
def get_draft_process(self, draftprocess_id: int) -> dict | None:
    """Get draft process data.

    Args:
        draftprocess_id (int): ID of an existing draft process

    Returns:
        dict | None: Get the details for a draft process.
                     Delivers None in case of an error.

        Example result:
        {
            'data': {
                'actions': [
                    {
                        'key': 'Initiate',
                        'label': 'Start'
                    }
                ],
                'attachment_centric_default_mode': 'properties',
                'attachments_on': True,
                'authentication': False,
                'comments_on': True,
                'data_packages': [...],
                'enableTopAlignedLabel': True,
                'instructions': 'Please pick the Approver (type-ahead search)\n\n',
                'process_id': 158037,
                'task': {...},
                'title': 'Contract Approval Workflow (1 step)',
                'workflow_type': '1_1'
            },
            'forms': [
                {...}
            ]
        }
    """

    request_url = (
        self.config()["draftProcessFormUrl"]
        + "/update"
        + "?draftprocess_id="
        + str(draftprocess_id)
    )
    request_header = self.request_form_header()

    logger.debug(
        "Get draft process with ID -> %s; calling -> %s",
        str(draftprocess_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get draft process with ID -> {}".format(
            draftprocess_id
        ),
    )

get_external_system_connection(connection_name, show_error=False)

Get Extended ECM external system connection (e.g. SAP, Salesforce, SuccessFactors).

Parameters:

Name Type Description Default
connection_name str

Name of the connection

required
show_error bool

If True, treat as error if connection is not found.

False

Returns: dict: External system Details or None if the REST call fails.

Source code in pyxecm/otcs.py
def get_external_system_connection(
    self, connection_name: str, show_error: bool = False
) -> dict | None:
    """Get Extended ECM external system connection (e.g. SAP, Salesforce, SuccessFactors).

    Args:
        connection_name (str): Name of the connection
        show_error (bool, optional): If True, treat as error if connection is not found.
    Returns:
        dict: External system Details or None if the REST call fails.
    """
    # Encode special characters in connection_name
    connection_name = connection_name.replace("\\", "0xF0A6").replace("/", "0xF0A7")
    request_url = (
        self.config()["externalSystemUrl"] + "/" + connection_name + "/config"
    )
    request_header = self.cookie()

    logger.debug(
        "Get external system connection -> %s; calling -> %s",
        connection_name,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        warning_message="External system connection -> '{}' does not yet exist".format(
            connection_name
        ),
        failure_message="Failed to get external system connection -> '{}'".format(
            connection_name
        ),
        show_error=show_error,
    )

get_group(name, show_error=False)

Lookup Content Server group.

Parameters:

Name Type Description Default
name str

name of the group

required
show_error bool

if True, treat as error if group is not found

False

Returns: dict: Group information or None if the group is not found. The returned information has a structure like this: "data": [ { "id": 0, "name": "string", ... } ] To access the id of the first group found use ["data"][0]["id"]

Source code in pyxecm/otcs.py
def get_group(self, name: str, show_error: bool = False) -> dict | None:
    """Lookup Content Server group.

    Args:
        name (str): name of the group
        show_error (bool): if True, treat as error if group is not found
    Returns:
        dict: Group information or None if the group is not found.
        The returned information has a structure like this:
        "data": [
            {
                "id": 0,
                "name": "string",
                ...
            }
        ]
        To access the id of the first group found use ["data"][0]["id"]
    """

    # Add query parameters (these are NOT passed via JSon body!)
    # type = 1 ==> Group
    query = {"where_type": 1, "where_name": name}
    encoded_query = urllib.parse.urlencode(query, doseq=True)
    request_url = self.config()["membersUrlv2"] + "?{}".format(encoded_query)

    request_header = self.request_form_header()

    logger.debug("Get group with name -> '%s'; calling -> %s", name, request_url)

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get group -> '{}'".format(name),
        warning_message="Group -> '{}' does not yet exist".format(name),
        show_error=show_error,
    )

get_group_members(group, member_type, limit=100)

Get Content Server group members.

Parameters:

Name Type Description Default
group int

ID of the group.

required
member_type int

users = 0, groups = 1

required
limit int

max number of results (internal default is 25)

100

Returns: dict: Group members or None if the group members couldn't be found.

Source code in pyxecm/otcs.py
def get_group_members(
    self, group: int, member_type: int, limit: int = 100
) -> dict | None:
    """Get Content Server group members.

    Args:
        group (int): ID of the group.
        member_type (int): users = 0, groups = 1
        limit (int, optional): max number of results (internal default is 25)
    Returns:
        dict: Group members or None if the group members couldn't be found.
    """

    # default limit is 25 which may not be enough for groups with many members
    # where_type = 1 makes sure we just get groups and not users
    request_url = (
        self.config()["membersUrlv2"]
        + "/"
        + str(group)
        + "/members?where_type="
        + str(member_type)
        + "&limit="
        + str(limit)
    )
    request_header = self.request_form_header()

    logger.debug(
        "Get members of group with ID -> %s; calling -> %s",
        str(group),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get members of group with ID -> {}".format(
            group
        ),
    )

get_json_document(node_id, version_number='')

Get document content from Extended ECM and read content as JSON.

Parameters:

Name Type Description Default
node_id int

node ID of the document to download

required
version_number str

version of the document to download. If version = "" then download the latest version.

''

Returns: list|dict: content of the file or None in case of an error.

Source code in pyxecm/otcs.py
def get_json_document(
    self, node_id: int, version_number: str = ""
) -> list | dict | None:
    """Get document content from Extended ECM and read content as JSON.

    Args:
        node_id (int): node ID of the document to download
        version_number (str, optional): version of the document to download.
                                        If version = "" then download the latest
                                        version.
    Returns:
        list|dict: content of the file or None in case of an error.
    """

    return self.get_document_content(
        node_id=node_id, version_number=version_number, parse_request_response=True
    )

get_latest_document_version(node_id)

Get latest version of a document node based on the node ID.

Returns: dict: Node information or None if no node with this ID is found.

Source code in pyxecm/otcs.py
def get_latest_document_version(self, node_id: int) -> dict | None:
    """Get latest version of a document node based on the node ID.

    Args:
        node_id (int) is the node Id of the node
    Returns:
        dict: Node information or None if no node with this ID is found.
    """

    request_url = (
        self.config()["nodesUrl"] + "/" + str(node_id) + "/versions/latest"
    )
    request_header = self.request_form_header()

    logger.debug(
        "Get latest version of document with node ID -> %s; calling -> %s",
        str(node_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get latest version of document with node ID -> {}".format(
            str(node_id)
        ),
    )

get_node(node_id, fields='properties', metadata=False, timeout=REQUEST_TIMEOUT)

Get a node based on the node ID.

Parameters:

Name Type Description Default
fields str | list

Which fields to retrieve. This can have a big impact on performance! Possible fields: * "properties" - can further be restricted by adding sub-fields in {...} like "properties{id,name,parent_id,description}" * "categories" * "versions" - can further be restricted by adding ".element(0)" to just get the latest version * "permissions" - canfurther be restricted by adding ".limit(5)" to just get the first 5 permissions fields can either be a string (to select just one field group) or a list of strings to select multiple groups

'properties'
metadata bool

Returns metadata (data type, field length, min/max values, etc.) about data, which will be returned under results.metadata / metadata_map / metadata_order

False
timeout int

timeout for the request in seconds

REQUEST_TIMEOUT

Returns: dict: Node information or None if no node with this ID is found.

Source code in pyxecm/otcs.py
def get_node(
    self,
    node_id: int,
    fields: (
        str | list
    ) = "properties",  # per default we just get the most important information
    metadata: bool = False,
    timeout: int = REQUEST_TIMEOUT,
) -> dict | None:
    """Get a node based on the node ID.

    Args:
        node_id (int) is the node Id of the node
        fields (str | list, optional): Which fields to retrieve. This can have a big impact on performance!
                                        Possible fields:
                                        * "properties" - can further be restricted by adding sub-fields in {...} like "properties{id,name,parent_id,description}"
                                        * "categories"
                                        * "versions" - can further be restricted by adding ".element(0)" to just get the latest version
                                        * "permissions" - canfurther be restricted by adding ".limit(5)" to just get the first 5 permissions
                                        fields can either be a string (to select just one field group) or a list of strings to select multiple groups
        metadata (bool, optional): Returns metadata (data type, field length, min/max values, etc.)
                                   about data, which will be returned under results.metadata /
                                   metadata_map / metadata_order
        timeout (int, optional): timeout for the request in seconds
    Returns:
        dict: Node information or None if no node with this ID is found.

    """

    query = {}
    if fields:
        query["fields"] = fields

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "?{}".format(encoded_query)
    )

    if metadata:
        request_url += "&metadata"

    request_header = self.request_form_header()

    logger.debug("Get node with ID -> %s; calling -> %s", str(node_id), request_url)

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=timeout,
        failure_message="Failed to get node with ID -> {}".format(node_id),
    )

get_node_actions(node_id, filter_actions=None)

Get allowed actions for a node.

Parameters:

Name Type Description Default
node_id int | list

ID(s) of the Node(s). This can either be int (= single node) or a list of nodes

required
filter_actions list

Optional list of actions to filter for, e.g. "delete", "copy", "permissions", "makefavorite", "open", "collect", "audit", ...

None

Returns: dict: Information of the Node actions or None if the request fails. "results" is a dictionary with Node IDs as keys, and three sub-sictionaries "data", "map", and "order.

Example:
{
    'links': {'data': {...}},
    'results': {
        '173301412': {
            'data': {
                'AddRMClassifications': {'body': '{"displayPrompt":false,"enabled":false,"inheritfrom":false,"managed":true}', 'content_type': 'application/x-www-form-urlencoded', 'form_href': '', 'href': '/api/v2/nodes/164878074/rmclassifications', 'method': 'POST', 'name': 'Add RM Classification'},
                'audit': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074/audit?limit=1000', 'method': 'GET', 'name': 'Audit'},
                'BrowseClassifiedItems': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074/nodes', 'method': 'GET', 'name': 'Browse classified items'},
                'BrowseRecManContainer': {'body': '', 'content_type': 'application/x-www-form-urlencoded', 'form_href': '', 'href': '', 'method': '', 'name': ''},
                'collect': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074', 'method': 'PUT', 'name': 'Collect'},
                'copy': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes', 'method': 'POST', 'name': 'Copy'},
                'makefavorite': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/members/favorites/164878074', 'method': 'POST', 'name': 'Add to Favorites'},
                'more': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': '...'},
                'open': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074/nodes', 'method': 'GET', 'name': 'Open'},
                'permissions': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': 'Permissions'}, 'preview': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': 'Preview'},
                'PrinteFile': {'body': '', 'content_type': '', 'form_href': '', 'href': 'api/v2/govprint', 'method': 'POST', 'name': 'Print'}, 'properties': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074', 'method': 'GET', 'name': 'Properties'},
                'SendOutlookReminder': {'body': '', 'content_type': '', 'form_href': '', 'href': 'api/v2/node/xgovoutlookreminder', 'method': 'POST', 'name': 'Send Outlook reminder'},
                'viewx-compare': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': 'viewx-compare'},
                'viewx-transform': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': 'viewx-transform'}},
            'map': {...},
            'order': [...]
        }
    }
Source code in pyxecm/otcs.py
def get_node_actions(
    self, node_id: int | list, filter_actions: list = None
) -> dict:
    """Get allowed actions for a node.

    Args:
        node_id (int | list): ID(s) of the Node(s). This can either be int (= single node) or a list of nodes
        filter_actions (list, optional): Optional list of actions to filter for,
                                         e.g. "delete", "copy", "permissions", "makefavorite", "open", "collect", "audit", ...
    Returns:
        dict: Information of the Node actions or None if the request fails. "results" is a dictionary with Node IDs as keys,
              and three sub-sictionaries "data", "map", and "order.

        Example:
        {
            'links': {'data': {...}},
            'results': {
                '173301412': {
                    'data': {
                        'AddRMClassifications': {'body': '{"displayPrompt":false,"enabled":false,"inheritfrom":false,"managed":true}', 'content_type': 'application/x-www-form-urlencoded', 'form_href': '', 'href': '/api/v2/nodes/164878074/rmclassifications', 'method': 'POST', 'name': 'Add RM Classification'},
                        'audit': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074/audit?limit=1000', 'method': 'GET', 'name': 'Audit'},
                        'BrowseClassifiedItems': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074/nodes', 'method': 'GET', 'name': 'Browse classified items'},
                        'BrowseRecManContainer': {'body': '', 'content_type': 'application/x-www-form-urlencoded', 'form_href': '', 'href': '', 'method': '', 'name': ''},
                        'collect': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074', 'method': 'PUT', 'name': 'Collect'},
                        'copy': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes', 'method': 'POST', 'name': 'Copy'},
                        'makefavorite': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/members/favorites/164878074', 'method': 'POST', 'name': 'Add to Favorites'},
                        'more': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': '...'},
                        'open': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074/nodes', 'method': 'GET', 'name': 'Open'},
                        'permissions': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': 'Permissions'}, 'preview': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': 'Preview'},
                        'PrinteFile': {'body': '', 'content_type': '', 'form_href': '', 'href': 'api/v2/govprint', 'method': 'POST', 'name': 'Print'}, 'properties': {'body': '', 'content_type': '', 'form_href': '', 'href': '/api/v2/nodes/164878074', 'method': 'GET', 'name': 'Properties'},
                        'SendOutlookReminder': {'body': '', 'content_type': '', 'form_href': '', 'href': 'api/v2/node/xgovoutlookreminder', 'method': 'POST', 'name': 'Send Outlook reminder'},
                        'viewx-compare': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': 'viewx-compare'},
                        'viewx-transform': {'body': '', 'content_type': '', 'form_href': '', 'href': '', 'method': '', 'name': 'viewx-transform'}},
                    'map': {...},
                    'order': [...]
                }
            }
    """

    if isinstance(node_id, list):
        actions_post_body = {"ids": node_id, "actions": filter_actions}
    else:
        actions_post_body = {"ids": [node_id], "actions": filter_actions}

    request_url = self.config()["nodesUrlv2"] + "/actions"

    request_header = self.request_form_header()

    logger.debug(
        "Get actions for node(s) with ID -> %s; calling -> %s",
        str(node_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=actions_post_body,
        timeout=None,
        failure_message="Failed to get actions for node with ID -> {}".format(
            node_id
        ),
    )

get_node_by_parent_and_name(parent_id, name, fields='properties', show_error=False, exact_match=True)

Get a node based on the parent ID and name. This method does basically a query with "where_name" and the "result" is a list.

Parameters:

Name Type Description Default
fields str | list

Which fields to retrieve. This can have a big impact on performance! Possible fields: * "properties" - can further be restricted by adding sub-fields in {...} like "properties{id,name,parent_id,description}" * "categories" * "versions" - can further be restricted by adding ".element(0)" to just get the latest version * "permissions" - canfurther be restricted by adding ".limit(5)" to just get the first 5 permissions fields can either be a string (to select just one field group) or a list of strings to select multiple groups

'properties'
show_error bool

treat as error if node is not found

False

Returns: dict: Node information or None if no node with this name is found in parent. Access to node ID with: response["results"][0]["data"]["properties"]["id"]

Source code in pyxecm/otcs.py
def get_node_by_parent_and_name(
    self,
    parent_id: int,
    name: str,
    fields: str | list = "properties",
    show_error: bool = False,
    exact_match: bool = True,
) -> dict | None:
    """Get a node based on the parent ID and name. This method does basically
       a query with "where_name" and the "result" is a list.

    Args:
        parent_id (int) is the node Id of the parent node
        name (str) is the name of the node to get
        fields (str | list, optional): Which fields to retrieve. This can have a big impact on performance!
                                        Possible fields:
                                        * "properties" - can further be restricted by adding sub-fields in {...} like "properties{id,name,parent_id,description}"
                                        * "categories"
                                        * "versions" - can further be restricted by adding ".element(0)" to just get the latest version
                                        * "permissions" - canfurther be restricted by adding ".limit(5)" to just get the first 5 permissions
                                        fields can either be a string (to select just one field group) or a list of strings to select multiple groups
        show_error (bool, optional): treat as error if node is not found
    Returns:
        dict: Node information or None if no node with this name is found in parent.
                    Access to node ID with: response["results"][0]["data"]["properties"]["id"]
    """

    # Add query parameters (these are NOT passed via JSon body!)
    query = {"where_name": name}
    if fields:
        query["fields"] = fields
    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(parent_id)
        + "/nodes?limit=100&{}".format(encoded_query)
    )
    request_header = self.request_form_header()

    logger.debug(
        "Get node with name -> '%s' and parent ID -> %s; calling -> %s",
        name,
        str(parent_id),
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        warning_message="Node with name -> '{}' and parent ID -> {} does not exist".format(
            name, parent_id
        ),
        failure_message="Failed to get node with name -> '{}' and parent ID -> {}".format(
            name, parent_id
        ),
        show_error=show_error,
    )

    # Filter results for exact matches only
    if exact_match:
        results = response.get("results", [])
        filtered_results = next(
            (
                node
                for node in results
                if node.get("data", {}).get("properties", {}).get("name") == name
            ),
            None,
        )

        response["results"] = [] if filtered_results is None else [filtered_results]

    return response

get_node_by_volume_and_path(volume_type, path=None, create_path=False)

Get a node based on the volume and path (list of container items).

Parameters:

Name Type Description Default
volume_type int

Volume type ID (default is 141 = Enterprise Workspace) "Records Management" = 550 "Content Server Document Templates" = 20541 "O365 Office Online Volume" = 1296 "Categories Volume" = 133 "Perspectives" = 908 "Perspective Assets" = 954 "Facets Volume" = 901 "Transport Warehouse" = 525 "Transport Warehouse Workbench" = 528 "Transport Warehouse Package" = 531 "Event Action Center Configuration" = 898 "Classification Volume" = 198 "Support Asset Volume" = 1309 "Physical Objects Workspace" = 413 "Extended ECM" = 882 "Enterprise Workspace" = 141 "Personal Workspace" = 142 "Business Workspaces" = 862

required
path list

list of container items (top down), last item is name of to be retrieved item. If path is empty the node of the volume is returned.

None
create_path bool

if path elements are missing: should they be created?

False

Returns: dict: Node information or None if no node with this path is found.

Source code in pyxecm/otcs.py
def get_node_by_volume_and_path(
    self, volume_type: int, path: list | None = None, create_path: bool = False
) -> dict | None:
    """Get a node based on the volume and path (list of container items).

    Args:
        volume_type (int): Volume type ID (default is 141 = Enterprise Workspace)
            "Records Management"                = 550
            "Content Server Document Templates" = 20541
            "O365 Office Online Volume"         = 1296
            "Categories Volume"                 = 133
            "Perspectives"                      = 908
            "Perspective Assets"                = 954
            "Facets Volume"                     = 901
            "Transport Warehouse"               = 525
            "Transport Warehouse Workbench"     = 528
            "Transport Warehouse Package"       = 531
            "Event Action Center Configuration" = 898
            "Classification Volume"             = 198
            "Support Asset Volume"              = 1309
            "Physical Objects Workspace"        = 413
            "Extended ECM"                      = 882
            "Enterprise Workspace"              = 141
            "Personal Workspace"                = 142
            "Business Workspaces"               = 862
        path (list): list of container items (top down), last item is name of to be retrieved item.
                     If path is empty the node of the volume is returned.
        create_path (bool): if path elements are missing: should they be created?
    Returns:
        dict: Node information or None if no node with this path is found.
    """

    # If path is not given we use empty list to make the for loop below working in this case as well
    if path is None:
        path = []

    # Preparation: get volume IDs for Transport Warehouse (root volume and Transport Packages)
    response = self.get_volume(volume_type)
    if not response:
        logger.error("Volume type -> %s not found!", str(volume_type))
        return None

    volume_id = self.get_result_value(response, "id")
    logger.debug(
        "Volume type -> %s has node ID -> %s", str(volume_type), str(volume_id)
    )

    current_item_id = volume_id

    # in case the path is an empty list
    # we will have the node of the volume:
    node = self.get_node(current_item_id)

    for path_element in path:
        node = self.get_node_by_parent_and_name(current_item_id, path_element)
        path_item_id = self.get_result_value(node, "id")
        if not path_item_id and create_path:
            node = self.create_item(
                parent_id=current_item_id, item_type=0, item_name=path_element
            )
            path_item_id = self.get_result_value(node, "id")
        if not path_item_id:
            logger.error(
                "Cannot find path element -> '%s' in container with ID -> %s.",
                path_element,
                str(current_item_id),
            )
            return None
        current_item_id = path_item_id
        logger.debug("Traversing path element with ID -> %s", str(current_item_id))

    return node

get_node_by_workspace_and_path(workspace_id, path, create_path=False, show_error=False)

Get a node based on the workspace ID (= node ID) and path (list of folder names).

Parameters:

Name Type Description Default
workspace_id int

node ID of the workspace

required
path list

list of container items (top down), last item is name of to be retrieved item. If path is empty the node of the volume is returned.

required
create_path bool

whether or not missing folders in the path should be created

False
show_error bool

treat as error if node is not found

False

Returns: dict: Node information or None if no node with this path is found.

Source code in pyxecm/otcs.py
def get_node_by_workspace_and_path(
    self,
    workspace_id: int,
    path: list,
    create_path: bool = False,
    show_error: bool = False,
) -> dict | None:
    """Get a node based on the workspace ID (= node ID) and path (list of folder names).

    Args:
        workspace_id (int): node ID of the workspace
        path (list): list of container items (top down), last item is name of to be retrieved item.
                     If path is empty the node of the volume is returned.
        create_path (bool): whether or not missing folders in the path should be created
        show_error (bool, optional): treat as error if node is not found
    Returns:
        dict: Node information or None if no node with this path is found.
    """

    parent_item_id = workspace_id

    # in case the path is an empty list
    # we will have the node of the workspace:
    node = self.get_node(parent_item_id)

    for path_element in path:
        node = self.get_node_by_parent_and_name(parent_item_id, path_element)
        current_item_id = self.get_result_value(node, "id")
        if not current_item_id:
            if create_path:
                # create missing path element:
                response = self.create_item(
                    parent_id=parent_item_id,
                    item_type=str(0),
                    item_name=path_element,
                    show_error=False,
                )
                # We may have a race condition here - another thread may have created the folder in parallel
                if not response:
                    logger.warning(
                        "Cannot create folder -> '%s' in workspace with ID -> %s (path -> %s), it may already exist (race condition). Try to get it...",
                        path_element,
                        workspace_id,
                        str(path),
                    )
                    response = self.get_node_by_parent_and_name(
                        parent_id=parent_item_id,
                        name=path_element,
                        show_error=True,
                    )
                    if not response:
                        if show_error:
                            logger.error(
                                "Cannot create path element -> %s!", path_element
                            )
                        else:
                            logger.debug(
                                "Cannot create path element -> %s.", path_element
                            )
                        return None
                # now we set current item ID to the new response:
                current_item_id = self.get_result_value(response, "id")
                node = response
            # end if create_path
            else:
                if show_error:
                    logger.error("Cannot find path element -> %s!", path_element)
                else:
                    logger.debug("Cannot find path element -> %s.", path_element)
                return None
        logger.debug(
            "Traversing path element -> '%s' (%s)",
            path_element,
            str(current_item_id),
        )
        parent_item_id = current_item_id

    return node

get_node_categories(node_id, metadata=True)

Get categories assigned to a node.

Parameters:

Name Type Description Default
node_id int

ID of the node to get the categories for.

required
metadata bool

expand the attribute definitions of the category. Default is True.

True

Returns: dict | None: category response or None if the call to the REST API fails.

Example:
[
    {
        'data': {
            'categories': {
                '16878_25': 'Customer',
                '16878_28': '50031',
                '16878_29': 'Global Trade AG',
                '16878_30': 'Gutleutstraße 53',
                '16878_31': 'Germany',
                '16878_32': '60329',
                '16878_33': ['1000'],
                '16878_34': 'Frankfurt',
                '16878_37': ['Retail'],
                '16878_38': '0000050031',
                '16878_39_1_40': '0000001096',
                '16878_39_1_41': 'Heinz Hart',
                '16878_39_1_42': 'Purchasing',
                '16878_39_1_43': 'Purchasing Manager',
                '16878_39_1_44': '+49695325410',
                '16878_39_1_45': '+49695325499',
                '16878_39_1_46': 'Heinz.Hart@GlobalTrade.com',
                '16878_39_1_47': 'B',
                '16878_39_1_48': '4',
                ...
            }
        },
        'metadata': {
            '16878': {
                'allow_undefined': False,
                'bulk_shared': False,
                'default_value': None,
                'description': None,
                'hidden': False,
                'key': '16878',
                'key_value_pairs': False,
                'multi_value': False,
                'multi_value_length_default': 1,
                'multi_value_length_fixed': True,
                'multi_value_length_max': 1,
                'multi_value_max_length': None,
                'multi_value_min_length': None,
                'multi_value_unique': False,
                'name': 'Customer',
                'next_id': 83,
                'persona': 'category',
                'read_only': True,
                'required': False,
                ...
            },
            '16878_25': {
                'allow_undefined': False,
                'bulk_shared': False,
                'default_value': None,
                'description': None,
                'hidden': False,
                'key': '16878_25',
                'key_value_pairs': False,
                'max_length': None,
                'min_length': None,
                'multi_select': False,
                'multi_value': False,
                'multi_value_length_default': 1,
                'multi_value_length_fixed': True,
                'multi_value_length_max': 1,
                'multi_value_max_length': None,
                'multi_value_min_length': None,
                'multi_value_unique': False,
                'multiline': False,
                'multilingual': False,
                ...
            },
            '16878_28': {
                'allow_undefined': False,
                'bulk_shared': False,
                'default_value': None,
                'description': None,
                'hidden': False,
                'key': '16878_28',
                'key_value_pairs': False,
                'max_length': 10,
                'min_length': None,
                'multi_select': False,
                'multi_value': False,
                'multi_value_length_default': 1,
                'multi_value_length_fixed': True,
                'multi_value_length_max': 1,
                'multi_value_max_length': None,
                'multi_value_min_length': None,
                'multi_value_unique': False,
                'multiline': False,
                'multilingual': False,
                ...
            },
            ...
        }
        'metadata_map': {
            'categories': {'16878': ['16878_2', '16878_3', '16878_4', '16878_5', '16878_6', '16878_7', '16878_8']}
        }
        'metadata_order': {
            'categories': ['16878']
        }
    }
]
Source code in pyxecm/otcs.py
def get_node_categories(self, node_id: int, metadata: bool = True) -> dict | None:
    """Get categories assigned to a node.

    Args:
        node_id (int): ID of the node to get the categories for.
        metadata (bool, optional): expand the attribute definitions of the category. Default is True.
    Returns:
        dict | None: category response or None if the call to the REST API fails.

        Example:
        [
            {
                'data': {
                    'categories': {
                        '16878_25': 'Customer',
                        '16878_28': '50031',
                        '16878_29': 'Global Trade AG',
                        '16878_30': 'Gutleutstraße 53',
                        '16878_31': 'Germany',
                        '16878_32': '60329',
                        '16878_33': ['1000'],
                        '16878_34': 'Frankfurt',
                        '16878_37': ['Retail'],
                        '16878_38': '0000050031',
                        '16878_39_1_40': '0000001096',
                        '16878_39_1_41': 'Heinz Hart',
                        '16878_39_1_42': 'Purchasing',
                        '16878_39_1_43': 'Purchasing Manager',
                        '16878_39_1_44': '+49695325410',
                        '16878_39_1_45': '+49695325499',
                        '16878_39_1_46': 'Heinz.Hart@GlobalTrade.com',
                        '16878_39_1_47': 'B',
                        '16878_39_1_48': '4',
                        ...
                    }
                },
                'metadata': {
                    '16878': {
                        'allow_undefined': False,
                        'bulk_shared': False,
                        'default_value': None,
                        'description': None,
                        'hidden': False,
                        'key': '16878',
                        'key_value_pairs': False,
                        'multi_value': False,
                        'multi_value_length_default': 1,
                        'multi_value_length_fixed': True,
                        'multi_value_length_max': 1,
                        'multi_value_max_length': None,
                        'multi_value_min_length': None,
                        'multi_value_unique': False,
                        'name': 'Customer',
                        'next_id': 83,
                        'persona': 'category',
                        'read_only': True,
                        'required': False,
                        ...
                    },
                    '16878_25': {
                        'allow_undefined': False,
                        'bulk_shared': False,
                        'default_value': None,
                        'description': None,
                        'hidden': False,
                        'key': '16878_25',
                        'key_value_pairs': False,
                        'max_length': None,
                        'min_length': None,
                        'multi_select': False,
                        'multi_value': False,
                        'multi_value_length_default': 1,
                        'multi_value_length_fixed': True,
                        'multi_value_length_max': 1,
                        'multi_value_max_length': None,
                        'multi_value_min_length': None,
                        'multi_value_unique': False,
                        'multiline': False,
                        'multilingual': False,
                        ...
                    },
                    '16878_28': {
                        'allow_undefined': False,
                        'bulk_shared': False,
                        'default_value': None,
                        'description': None,
                        'hidden': False,
                        'key': '16878_28',
                        'key_value_pairs': False,
                        'max_length': 10,
                        'min_length': None,
                        'multi_select': False,
                        'multi_value': False,
                        'multi_value_length_default': 1,
                        'multi_value_length_fixed': True,
                        'multi_value_length_max': 1,
                        'multi_value_max_length': None,
                        'multi_value_min_length': None,
                        'multi_value_unique': False,
                        'multiline': False,
                        'multilingual': False,
                        ...
                    },
                    ...
                }
                'metadata_map': {
                    'categories': {'16878': ['16878_2', '16878_3', '16878_4', '16878_5', '16878_6', '16878_7', '16878_8']}
                }
                'metadata_order': {
                    'categories': ['16878']
                }
            }
        ]
    """

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/categories"
    if metadata:
        request_url += "?metadata"
    request_header = self.request_form_header()

    logger.debug(
        "Get categories of node with ID -> %s; calling -> %s",
        str(node_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get categories for node ID -> {}".format(
            str(node_id)
        ),
    )

get_node_category(node_id, category_id, metadata=True)

Get a specific category assigned to a node.

Parameters:

Name Type Description Default
node_id int

ID of the node to get the categories for.

required
category_id int

ID of the category definition ID (in category volume)

required
metadata bool

expand the attribute definitions of the category. Default is True

True

Returns: dict: category response or None if the call to the REST API fails.

Source code in pyxecm/otcs.py
def get_node_category(
    self, node_id: int, category_id: int, metadata: bool = True
) -> dict | None:
    """Get a specific category assigned to a node.

    Args:
        node_id (int): ID of the node to get the categories for.
        category_id (int): ID of the category definition ID (in category volume)
        metadata (bool, optional): expand the attribute definitions of the category. Default is True
    Returns:
        dict: category response or None if the call to the REST API fails.
    """

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "/categories/"
        + str(category_id)
    )
    if metadata:
        request_url += "?metadata"
    request_header = self.request_form_header()

    logger.debug(
        "Get category with ID -> %s on node with ID -> %s; calling -> %s",
        str(category_id),
        str(node_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get category with ID -> {} for node ID -> {}".format(
            category_id, node_id
        ),
    )

get_node_category_definition(node_id, category_name)

Get category definition (category id and attribute names, IDs and types). This is a convenience method that wraps the the complex return value of get_node_categories() in an easier to parse structure.

Parameters:

Name Type Description Default
node_id int

node to read the category definition from (e.g. a workspace template or a document template or a target folder) This should NOT be the category definition object!

required
category_name str

name of the category

required

Returns: int: category ID dict: dict keys are the attribute names. dict values are sub-dictionaries with the id and type of the attribute. For set attributes the key is constructed as :. Set attributes also incluide an additional value "set_id".

Example response:
{
    'Status': {'id': '16892_25', 'type': 'String'},
    'Customer Number': {'id': '16892_28', 'type': 'String'},
    'Name': {'id': '16892_29', 'type': 'String'},
    'Street': {'id': '16892_30', 'type': 'String'},
    'Country': {'id': '16892_31', 'type': 'String'},
    'Postal code': {'id': '16892_32', 'type': 'String'},
    'Sales organisation': {'id': '16892_33', 'type': 'String'},
    'City': {'id': '16892_34', 'type': 'String'},
    'Industry': {'id': '16892_37', 'type': 'String'},
    'Object Key': {'id': '16892_38', 'type': 'String'},
    'Contacts': {'id': '16892_39', 'type': 'set'},
    'Contacts:BP No': {'id': '16892_39_x_40', 'type': 'String', 'set_id': '16892_39'},
    'Contacts:Name': {'id': '16892_39_x_41', 'type': 'String', 'set_id': '16892_39'},
    'Contacts:Department': {'id': '16892_39_x_42', 'type': 'String', 'set_id': '16892_39'},
    'Contacts:Function': {'id': '16892_39_x_43', 'type': 'String', 'set_id': '16892_39'},
    'Contacts:Phone': {'id': '16892_39_x_44', 'type': 'String', 'set_id': '16892_39'},
    'Contacts:Fax': {'id': '16892_39_x_45', 'type': 'String', 'set_id': '16892_39'},
    'Contacts:Email': {'id': '16892_39_x_46', 'type': 'String', 'set_id': '16892_39'},
    'Contacts:Building': {'id': '16892_39_x_47', 'type': 'String', 'set_id': '16892_39'},
    'Contacts:Floor': {'id': '16892_39_x_48', 'type': 'String', 'set_id': '16892_39'},
    'Contacts:Room': {'id': '16892_39_x_49', 'type': 'String', 'set_id': '16892_39'},
    'Contacts:Comments': {'id': '16892_39_x_50', 'type': 'String', 'set_id': '16892_39'},
    'Contacts:Valid from': {'id': '16892_39_x_51', 'type': 'Date', 'set_id': '16892_39'},
    'Contacts:Valid to': {'id': '16892_39_x_52', 'type': 'Date', 'set_id': '16892_39'},
    'Sales Areas': {'id': '16892_53', 'type': 'set'},
    'Sales Areas:Sales Organisation': {'id': '16892_53_x_54', 'type': 'String', 'set_id': '16892_53'},
    'Sales Areas:Distribution Channel': {'id': '16892_53_x_55', 'type': 'String', 'set_id': '16892_53'},
    'Sales Areas:Division': {'id': '16892_53_x_56', 'type': 'String', 'set_id': '16892_53'},
    'Rating': {'id': '16892_57', 'type': 'set'},
    'Rating:Credit Standing': {'id': '16892_57_x_58', 'type': 'String', 'set_id': '16892_57'},
    'Rating:Date': {'id': '16892_57_x_59', 'type': 'Date', 'set_id': '16892_57'},
    'Rating:Status': {'id': '16892_57_x_60', 'type': 'String', 'set_id': '16892_57'},
    'Rating:add. Information': {'id': '16892_57_x_61', 'type': 'String', 'set_id': '16892_57'},
    'Rating:Institute': {'id': '16892_57_x_62', 'type': 'String', 'set_id': '16892_57'},
    'Rating:Rating': {'id': '16892_57_x_63', 'type': 'String', 'set_id': '16892_57'},
    'Locations': {'id': '16892_75', 'type': 'set'},
    'Locations:Type': {'id': '16892_75_x_76', 'type': 'String', 'set_id': '16892_75'},
    'Locations:Street': {'id': '16892_75_x_77', 'type': 'String', 'set_id': '16892_75'},
    'Locations:City': {'id': '16892_75_x_78', 'type': 'String', 'set_id': '16892_75'},
    'Locations:Country': {'id': '16892_75_x_79', 'type': 'String', 'set_id': '16892_75'},
    'Locations:Postal code': {'id': '16892_75_x_80', 'type': 'String', 'set_id': '16892_75'},
    'Locations:Valid from': {'id': '16892_75_x_81', 'type': 'Date', 'set_id': '16892_75'},
    'Locations:Valid to': {'id': '16892_75_x_82', 'type': 'Date', 'set_id': '16892_75'}
}
Source code in pyxecm/otcs.py
def get_node_category_definition(
    self,
    node_id: int,
    category_name: str,
) -> tuple[int, dict]:
    """Get category definition (category id and attribute names, IDs and types).
       This is a convenience method that wraps the the complex return value
       of get_node_categories() in an easier to parse structure.

    Args:
        node_id (int): node to read the category definition from
                       (e.g. a workspace template or a document template or a target folder)
                       This should NOT be the category definition object!
        category_name (str): name of the category
    Returns:
        int: category ID
        dict: dict keys are the attribute names. dict values are sub-dictionaries with the id and type of the attribute.
              For set attributes the key is constructed as <set name>:<attribute name>.
              Set attributes also incluide an additional value "set_id".

        Example response:
        {
            'Status': {'id': '16892_25', 'type': 'String'},
            'Customer Number': {'id': '16892_28', 'type': 'String'},
            'Name': {'id': '16892_29', 'type': 'String'},
            'Street': {'id': '16892_30', 'type': 'String'},
            'Country': {'id': '16892_31', 'type': 'String'},
            'Postal code': {'id': '16892_32', 'type': 'String'},
            'Sales organisation': {'id': '16892_33', 'type': 'String'},
            'City': {'id': '16892_34', 'type': 'String'},
            'Industry': {'id': '16892_37', 'type': 'String'},
            'Object Key': {'id': '16892_38', 'type': 'String'},
            'Contacts': {'id': '16892_39', 'type': 'set'},
            'Contacts:BP No': {'id': '16892_39_x_40', 'type': 'String', 'set_id': '16892_39'},
            'Contacts:Name': {'id': '16892_39_x_41', 'type': 'String', 'set_id': '16892_39'},
            'Contacts:Department': {'id': '16892_39_x_42', 'type': 'String', 'set_id': '16892_39'},
            'Contacts:Function': {'id': '16892_39_x_43', 'type': 'String', 'set_id': '16892_39'},
            'Contacts:Phone': {'id': '16892_39_x_44', 'type': 'String', 'set_id': '16892_39'},
            'Contacts:Fax': {'id': '16892_39_x_45', 'type': 'String', 'set_id': '16892_39'},
            'Contacts:Email': {'id': '16892_39_x_46', 'type': 'String', 'set_id': '16892_39'},
            'Contacts:Building': {'id': '16892_39_x_47', 'type': 'String', 'set_id': '16892_39'},
            'Contacts:Floor': {'id': '16892_39_x_48', 'type': 'String', 'set_id': '16892_39'},
            'Contacts:Room': {'id': '16892_39_x_49', 'type': 'String', 'set_id': '16892_39'},
            'Contacts:Comments': {'id': '16892_39_x_50', 'type': 'String', 'set_id': '16892_39'},
            'Contacts:Valid from': {'id': '16892_39_x_51', 'type': 'Date', 'set_id': '16892_39'},
            'Contacts:Valid to': {'id': '16892_39_x_52', 'type': 'Date', 'set_id': '16892_39'},
            'Sales Areas': {'id': '16892_53', 'type': 'set'},
            'Sales Areas:Sales Organisation': {'id': '16892_53_x_54', 'type': 'String', 'set_id': '16892_53'},
            'Sales Areas:Distribution Channel': {'id': '16892_53_x_55', 'type': 'String', 'set_id': '16892_53'},
            'Sales Areas:Division': {'id': '16892_53_x_56', 'type': 'String', 'set_id': '16892_53'},
            'Rating': {'id': '16892_57', 'type': 'set'},
            'Rating:Credit Standing': {'id': '16892_57_x_58', 'type': 'String', 'set_id': '16892_57'},
            'Rating:Date': {'id': '16892_57_x_59', 'type': 'Date', 'set_id': '16892_57'},
            'Rating:Status': {'id': '16892_57_x_60', 'type': 'String', 'set_id': '16892_57'},
            'Rating:add. Information': {'id': '16892_57_x_61', 'type': 'String', 'set_id': '16892_57'},
            'Rating:Institute': {'id': '16892_57_x_62', 'type': 'String', 'set_id': '16892_57'},
            'Rating:Rating': {'id': '16892_57_x_63', 'type': 'String', 'set_id': '16892_57'},
            'Locations': {'id': '16892_75', 'type': 'set'},
            'Locations:Type': {'id': '16892_75_x_76', 'type': 'String', 'set_id': '16892_75'},
            'Locations:Street': {'id': '16892_75_x_77', 'type': 'String', 'set_id': '16892_75'},
            'Locations:City': {'id': '16892_75_x_78', 'type': 'String', 'set_id': '16892_75'},
            'Locations:Country': {'id': '16892_75_x_79', 'type': 'String', 'set_id': '16892_75'},
            'Locations:Postal code': {'id': '16892_75_x_80', 'type': 'String', 'set_id': '16892_75'},
            'Locations:Valid from': {'id': '16892_75_x_81', 'type': 'Date', 'set_id': '16892_75'},
            'Locations:Valid to': {'id': '16892_75_x_82', 'type': 'Date', 'set_id': '16892_75'}
        }
    """

    attribute_definitions = {}

    response = self.get_node_categories(node_id)
    if response and response["results"]:
        for categories in response["results"]:
            # get all metadata IDs
            keys = categories["metadata"]["categories"].keys()
            # There's one without an underscore - that's the ID of the category itself:
            cat_id = next((key for key in keys if "_" not in key), -1)
            cat_name = categories["metadata"]["categories"][cat_id]["name"]
            # Check we have the category we are looking for:
            if cat_name != category_name:
                # Wrong category - not matching - go to next
                continue
            for att_id in categories["metadata"]["categories"]:
                if not "_" in att_id:
                    # We skip the element representing the category itself:
                    continue
                att_name = categories["metadata"]["categories"][att_id]["name"]
                att_persona = categories["metadata"]["categories"][att_id][
                    "persona"
                ]
                # Persona can be either "set" or "categoryattribute".
                # If the persona is "set" we store the set information:
                if att_persona == "set":
                    # We save the set name and ID for the attributes that follow:
                    set_name = att_name
                    set_id = att_id
                # Attribute types can be "String", ...
                # For the set attribute itself the type_name = "Assoc"
                att_type = categories["metadata"]["categories"][att_id]["type_name"]
                if "_x_" in att_id:  # this is not true for the set attribute itself
                    # set_name and set_id are still set to the name of the proceeding
                    # for-loop iteration!
                    attribute_definitions[set_name + ":" + att_name] = {
                        "id": att_id,
                        "type": att_type,
                        "set_id": set_id,
                    }
                else:
                    attribute_definitions[att_name] = {
                        "id": att_id,
                        "type": att_type,
                    }

            return cat_id, attribute_definitions
    return -1, {}

get_node_category_ids(node_id)

Get list of all category definition IDs that are assign to the node.

Parameters:

Name Type Description Default
node_id int

ID of the node to get the categories for.

required

Returns: list: list of category IDs (all categories assigned to the node)

Source code in pyxecm/otcs.py
def get_node_category_ids(self, node_id: int) -> list:
    """Get list of all category definition IDs that are assign to the node.

    Args:
        node_id (int): ID of the node to get the categories for.
    Returns:
        list: list of category IDs (all categories assigned to the node)
    """

    categories = self.get_node_categories(node_id)
    if not categories or not categories["results"]:
        return None

    category_id_list = []

    for category in categories["results"]:
        category_id_list += [
            int(i) for i in category["metadata_order"]["categories"]
        ]

    return category_id_list

get_node_category_names(node_id)

Get list of all category names that are assign to the node.

Parameters:

Name Type Description Default
node_id int

ID of the node to get the categories for.

required

Returns: list: list of category names (all categories assigned to the node)

Source code in pyxecm/otcs.py
def get_node_category_names(self, node_id: int) -> list | None:
    """Get list of all category names that are assign to the node.

    Args:
        node_id (int): ID of the node to get the categories for.
    Returns:
        list: list of category names (all categories assigned to the node)
    """

    categories = self.get_node_categories(node_id=node_id, metadata=True)
    if not categories or not categories["results"]:
        return None

    # List comprehension to extract category names safely
    return [
        next(iter(category["metadata"]["categories"].values()), {}).get("name")
        for category in categories["results"]
    ]

get_node_columns(node_id)

Get custom columns configured / enabled for a node.

Parameters:

Name Type Description Default
node_id int

ID of the Node.

required

Returns: dict: Information of the Node columns or None if the request fails.

Example:
{
    'links': {
        'data': {...}
    },
    'results': {
        'columns_to_display': {
            'global_columns': ['Type', 'Name', 'Size', 'Modified'],
            'inherited_columns': [
                {
                    'id': 6270,
                    'name': 'Title',
                    'locked': False,
                    'default': False,
                    'has_permission': True,
                    'location_id': 6271,
                    'displayed': False,
                    'location_name': 'Knowledge Base Articles'
                },
                {
                    'id': 13076,
                    'name': 'Published Date',
                    'locked': False,
                    'default': False,
                    'has_permission': True,
                    'location_id': 6271,
                    'displayed': False,
                    'location_name': 'Knowledge Base Articles'
                },
                {
                    'id': 6248,
                    'name': 'Valid To Date',
                    'locked': False,
                    'default': False,
                    'has_permission': True,
                    'location_id': 6271,
                    'displayed': False,
                    'location_name': 'Knowledge Base Articles'
                },
                ...
            ],
            'local_columns': {
                'available_columns': [
                    {
                        'id': 13072,
                        'name': 'Application',
                        'default': False
                    },
                    {
                        'id': 6288,
                        'name': 'Approved Usage',
                        'default': False
                    },
                    {
                        'id': 6262,
                        'name': 'Business Function',
                        'default': False
                    },
                    ...
                ],
                'displayed_columns': [...]
            }
        },
        'columns_to_sort': {
            'inherited_sort': {
                'column_id': None,
                'column_name': None,
                'sort_direction': None
            },
            'local_sort': {
                'local_sort_column': [
                    {
                        'value': 13072,
                        'name': 'Application',
                        'selected': False
                    },
                    {
                        'value': 6288,
                        'name': 'Approved Usage',
                        'selected': False
                    },
                    ...
                ],
                'local_sort_order': [...]
            }
        }
    }
}
Source code in pyxecm/otcs.py
def get_node_columns(self, node_id: int) -> dict:
    """Get custom columns configured / enabled for a node.

    Args:
        node_id (int): ID of the Node.
    Returns:
        dict: Information of the Node columns or None if the request fails.

        Example:
        {
            'links': {
                'data': {...}
            },
            'results': {
                'columns_to_display': {
                    'global_columns': ['Type', 'Name', 'Size', 'Modified'],
                    'inherited_columns': [
                        {
                            'id': 6270,
                            'name': 'Title',
                            'locked': False,
                            'default': False,
                            'has_permission': True,
                            'location_id': 6271,
                            'displayed': False,
                            'location_name': 'Knowledge Base Articles'
                        },
                        {
                            'id': 13076,
                            'name': 'Published Date',
                            'locked': False,
                            'default': False,
                            'has_permission': True,
                            'location_id': 6271,
                            'displayed': False,
                            'location_name': 'Knowledge Base Articles'
                        },
                        {
                            'id': 6248,
                            'name': 'Valid To Date',
                            'locked': False,
                            'default': False,
                            'has_permission': True,
                            'location_id': 6271,
                            'displayed': False,
                            'location_name': 'Knowledge Base Articles'
                        },
                        ...
                    ],
                    'local_columns': {
                        'available_columns': [
                            {
                                'id': 13072,
                                'name': 'Application',
                                'default': False
                            },
                            {
                                'id': 6288,
                                'name': 'Approved Usage',
                                'default': False
                            },
                            {
                                'id': 6262,
                                'name': 'Business Function',
                                'default': False
                            },
                            ...
                        ],
                        'displayed_columns': [...]
                    }
                },
                'columns_to_sort': {
                    'inherited_sort': {
                        'column_id': None,
                        'column_name': None,
                        'sort_direction': None
                    },
                    'local_sort': {
                        'local_sort_column': [
                            {
                                'value': 13072,
                                'name': 'Application',
                                'selected': False
                            },
                            {
                                'value': 6288,
                                'name': 'Approved Usage',
                                'selected': False
                            },
                            ...
                        ],
                        'local_sort_order': [...]
                    }
                }
            }
        }
    """

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/columns"

    request_header = self.request_form_header()

    logger.debug(
        "Get columns for node with ID -> %s; calling -> %s",
        str(node_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get columns for node with ID -> {}".format(
            node_id
        ),
    )

get_node_from_nickname(nickname, show_error=False)

Get a node based on the nickname.

Parameters:

Name Type Description Default
nickname str

Nickname of the node.

required
show_error bool

treat as error if node is not found

False

Returns: dict: Node information or None if no node with this nickname is found.

Source code in pyxecm/otcs.py
def get_node_from_nickname(
    self, nickname: str, show_error: bool = False
) -> dict | None:
    """Get a node based on the nickname.

    Args:
        nickname (str): Nickname of the node.
        show_error (bool): treat as error if node is not found
    Returns:
        dict: Node information or None if no node with this nickname is found.
    """

    request_url = self.config()["nicknameUrl"] + "/" + nickname + "/nodes"
    request_header = self.request_form_header()

    logger.debug(
        "Get node with nickname -> '%s'; calling -> %s", nickname, request_url
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        warning_message="Node with nickname -> '{}' does not exist".format(
            nickname
        ),
        failure_message="Failed to get node with nickname -> '{}'".format(nickname),
        show_error=show_error,
    )

get_process_task(process_id, subprocess_id=None, task_id=1)

Get the task information of a workflow assignment. This method must be called with the user authenticated that has the task in ts inbox.

    Args:
        process_id (int): process ID of the workflow instance
        subprocess_id (int | None, optional): Subprocess ID. Defaults to None (= process_id).
        task_id (int, optional): Task ID. Defaults to 1.

    Returns:
        dict | None: Response of REST API call. None in case an error occured.

        Example:
        {
            'data': {
                'actions': [
                    {
                        'key': 'Delegate',
                        'label': 'Forward'
                    }
                ],
                'attachments_on': True,
                'authentication': False,
                'comments_on': True,
                'custom_actions': [
                    {
                        'key': 'Approve',
                        'label': 'Approve'
                    },
                    {
                        'key': 'Reject',
                        'label': 'Reject'
                    }
                ],
                'data_packages': [
                    {
                        'data': {
                            'attachment_folder_id': 115292
                        },
                        'sub_type': 1,
                        'type': 1
                    }
                ],
                'instructions': 'Paul Williams has sent this contract to you for review.
  1. Read the attached document in-depth
  2. Enter the approval date
  3. Then click the Approve or Reject button
  4. Enter a Comment if prompted', 'message': None, 'process_id': 115295, 'subprocess_id': 115295, 'task': {...}, 'task_id': 1, 'title': 'Approver' }, 'forms': [ {...} ] }
Source code in pyxecm/otcs.py
def get_process_task(
    self, process_id: int, subprocess_id: int | None = None, task_id: int = 1
) -> dict | None:
    """Get the task information of a workflow assignment.
       This method must be called with the user authenticated
       that has the task in ts inbox.

    Args:
        process_id (int): process ID of the workflow instance
        subprocess_id (int | None, optional): Subprocess ID. Defaults to None (= process_id).
        task_id (int, optional): Task ID. Defaults to 1.

    Returns:
        dict | None: Response of REST API call. None in case an error occured.

        Example:
        {
            'data': {
                'actions': [
                    {
                        'key': 'Delegate',
                        'label': 'Forward'
                    }
                ],
                'attachments_on': True,
                'authentication': False,
                'comments_on': True,
                'custom_actions': [
                    {
                        'key': 'Approve',
                        'label': 'Approve'
                    },
                    {
                        'key': 'Reject',
                        'label': 'Reject'
                    }
                ],
                'data_packages': [
                    {
                        'data': {
                            'attachment_folder_id': 115292
                        },
                        'sub_type': 1,
                        'type': 1
                    }
                ],
                'instructions': 'Paul Williams has sent this contract to you for review. \n\n1. Read the attached document in-depth\n2. Enter the approval date\n3. Then click the Approve or Reject button\n4. Enter a Comment if prompted',
                'message': None,
                'process_id': 115295,
                'subprocess_id': 115295,
                'task': {...},
                'task_id': 1,
                'title': 'Approver'
            },
            'forms': [
                {...}
            ]
        }
    """

    if subprocess_id is None:
        subprocess_id = process_id

    request_url = (
        self.config()["processTaskUrl"]
        + "?process_id="
        + str(process_id)
        + "&subprocess_id="
        + str(subprocess_id)
        + "&task_id="
        + str(task_id)
    )
    request_header = self.request_form_header()

    logger.debug(
        "Get a process (workflow instance) task for process with ID -> %s; calling -> %s",
        str(process_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get task for process with ID -> {}".format(
            process_id
        ),
    )

get_records_management_codes()

Get Records Management Codes. These are the most basic data types of the Records Management configuration and required to create RSIs and other higher-level Records Management configurations

Returns: dict: RM codes or None if the request fails.

Source code in pyxecm/otcs.py
def get_records_management_codes(self) -> dict | None:
    """Get Records Management Codes. These are the most basic data types of
       the Records Management configuration and required to create RSIs and
       other higher-level Records Management configurations

    Args:
        None
    Returns:
        dict: RM codes or None if the request fails.
    """

    request_url = self.config()["recordsManagementUrlv2"] + "/rmcodes"
    request_header = self.request_form_header()

    logger.debug("Get list of Records Management codes; calling -> %s", request_url)

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get list of Records Management codes",
    )

    if response and "results" in response and response["results"]:
        return response["results"]["data"]

    return None

get_records_management_holds()

Get a list of all Records Management Holds in the system. Even though there are folders in the holds management area in RM these are not real folders - they cannot be retrieved with get_node_by_parent_and_name() thus we need this method to get them all.

Returns: dict: Response with list of holds: "results": { "data": { "holds": [ { "HoldID": 0, "HoldName": "string", "ActiveHold": 0, "OBJECT": 0, "ApplyPatron": "string", "DateApplied": "string", "HoldComment": "string", "HoldType": "string", "DateToRemove": "string", "DateRemoved": "string", "RemovalPatron": "string", "RemovalComment": "string", "EditDate": "string", "EditPatron": "string", "AlternateHoldID": 0, "ParentID": 0 } ] } }

Source code in pyxecm/otcs.py
def get_records_management_holds(self) -> dict | None:
    """Get a list of all Records Management Holds in the system. Even though there are folders
    in the holds management area in RM these are not real folders - they cannot be retrieved
    with get_node_by_parent_and_name() thus we need this method to get them all.

    Args:
        None
    Returns:
        dict: Response with list of holds:
        "results": {
            "data": {
                "holds": [
                    {
                        "HoldID": 0,
                        "HoldName": "string",
                        "ActiveHold": 0,
                        "OBJECT": 0,
                        "ApplyPatron": "string",
                        "DateApplied": "string",
                        "HoldComment": "string",
                        "HoldType": "string",
                        "DateToRemove": "string",
                        "DateRemoved": "string",
                        "RemovalPatron": "string",
                        "RemovalComment": "string",
                        "EditDate": "string",
                        "EditPatron": "string",
                        "AlternateHoldID": 0,
                        "ParentID": 0
                    }
                ]
            }
        }
    """

    request_url = self.config()["holdsUrlv2"]

    request_header = self.request_form_header()

    logger.debug("Get list of Records Management Holds; calling -> %s", request_url)

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get list of Records Management Holds",
    )

get_records_management_rsis(limit=100)

Get all Records management RSIs togther with their RSI Schedules.

Parameters:

Name Type Description Default
limit int

max elements to return (default = 100)

100

Returns: list: list of Records Management RSIs or None if the request fails. Each RSI list element is a dict with this structure: { "RSIID": 0, "RSI": "string", "Title": "string", "Subject": "string", "Description": "string", "CreateDate": "string", "RSIStatus": "string", "StatusDate": "string", "DiscontFlag": 0, "DiscontDate": "string", "DiscontComment": "string", "Active": 0, "DispControl": 0, "RSIScheduleID": 0, "RetStage": "string", "RecordType": 0, "EventType": 0, "RSIRuleCode": "string", "DateToUse": "string", "YearEndMonth": 0, "YearEndDay": 0, "RetYears": 0, "RetMonths": 0, "RetDays": 0, "RetIntervals": 0, "EventRuleDate": "string", "EventRule": "string", "EventComment": "string", "StageAction": "string", "FixedRet": 0, "ActionCode": "string", "ActionDescription": "string", "Disposition": "string", "ApprovalFlag": 0, "MaximumRet": 0, "ObjectType": "LIV" }

Source code in pyxecm/otcs.py
def get_records_management_rsis(self, limit: int = 100) -> list | None:
    """Get all Records management RSIs togther with their RSI Schedules.

    Args:
        limit (int, optional): max elements to return (default = 100)
    Returns:
        list: list of Records Management RSIs or None if the request fails.
        Each RSI list element is a dict with this structure:
        {
            "RSIID": 0,
            "RSI": "string",
            "Title": "string",
            "Subject": "string",
            "Description": "string",
            "CreateDate": "string",
            "RSIStatus": "string",
            "StatusDate": "string",
            "DiscontFlag": 0,
            "DiscontDate": "string",
            "DiscontComment": "string",
            "Active": 0,
            "DispControl": 0,
            "RSIScheduleID": 0,
            "RetStage": "string",
            "RecordType": 0,
            "EventType": 0,
            "RSIRuleCode": "string",
            "DateToUse": "string",
            "YearEndMonth": 0,
            "YearEndDay": 0,
            "RetYears": 0,
            "RetMonths": 0,
            "RetDays": 0,
            "RetIntervals": 0,
            "EventRuleDate": "string",
            "EventRule": "string",
            "EventComment": "string",
            "StageAction": "string",
            "FixedRet": 0,
            "ActionCode": "string",
            "ActionDescription": "string",
            "Disposition": "string",
            "ApprovalFlag": 0,
            "MaximumRet": 0,
            "ObjectType": "LIV"
        }
    """

    request_url = self.config()["rsisUrl"] + "?limit=" + str(limit)
    request_header = self.request_form_header()

    logger.debug("Get list of Records Management RSIs; calling -> %s", request_url)

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get list of Records Management RSIs",
    )

    if response and "results" in response and response["results"]:
        return response["results"]["data"]["rsis"]

    return None

get_result_value(response, key, index=0, property_name='properties', show_error=True)

Read an item value from the REST API response. This is considering the most typical structures delivered by V2 REST API of Extended ECM. See developer.opentext.com for more details.

Parameters:

Name Type Description Default
response dict

REST API response object

required
key str

key to find (e.g. "id", "name", ...)

required
index int

In case a list of results is delivered the index to use (1st element has index 0). Defaults to 0.

0
property_name str

name of the sub dictionary holding the actual values. Default is "properties".

'properties'

Returns: str: value of the item with the given key for None if no value is found for the given key.

Source code in pyxecm/otcs.py
def get_result_value(
    self,
    response: dict,
    key: str,
    index: int = 0,
    property_name: str = "properties",
    show_error: bool = True,
) -> str | None:
    """Read an item value from the REST API response. This is considering
       the most typical structures delivered by V2 REST API of Extended ECM.
       See developer.opentext.com for more details.

    Args:
        response (dict): REST API response object
        key (str): key to find (e.g. "id", "name", ...)
        index (int, optional): In case a list of results is delivered the index
                               to use (1st element has index  0). Defaults to 0.
        property_name (str, optional): name of the sub dictionary holding the actual values.
                                       Default is "properties".
    Returns:
        str: value of the item with the given key for None if no value is found for the given key.
    """

    # First do some sanity checks:
    if not response:
        logger.debug("Empty REST response - returning None")
        return None
    if not "results" in response:
        if show_error:
            logger.error("No 'results' key in REST response - returning None")
        return None

    results = response["results"]
    if not results:
        logger.debug("No results found!")
        return None

    # check if results is a list or a dict (both is possible - dependent on the actual REST API):
    if isinstance(results, dict):
        # result is a dict - we don't need index value

        # this is a special treatment for the businessworkspaces REST API - it returns
        # for "Create business workspace" the ID directly in the results dict (without data substructure)
        if key in results:
            return results[key]
        data = results["data"]
        if isinstance(data, dict):
            # data is a dict - we don't need index value:
            properties = data[property_name]
        elif isinstance(data, list):
            # data is a list - this has typically just one item, so we use 0 as index
            properties = data[0][property_name]
        else:
            logger.error(
                "Data needs to be a list or dict but it is -> %s", str(type(data))
            )
            return None
        logger.debug("Properties of results (dict) -> %s", str(properties))
        # For nearly all OTCS REST Calls perperties is a dict:
        if isinstance(properties, dict):
            if not key in properties:
                if show_error:
                    logger.error("Key -> '%s' is not in result properties!", key)
                return None
            return properties[key]
        # but there are some strange ones that have other names for
        # properties and may use a list - see e.g. /v2/holds
        elif isinstance(properties, list):
            if index > len(properties) - 1:
                logger.error(
                    "Illegal Index -> %s given. List has only -> %s elements!",
                    str(index),
                    str(len(properties)),
                )
                return None
            return properties[index][key]
        else:
            logger.error(
                "Properties needs to be a list or dict but it is -> %s",
                str(type(properties)),
            )
            return None
    elif isinstance(results, list):
        # result is a list - we need a valid index:
        if index > len(results) - 1:
            logger.error(
                "Illegal Index -> %s given. List has only -> %s elements!",
                str(index),
                str(len(results)),
            )
            return None
        data = results[index]["data"]
        if isinstance(data, dict):
            # data is a dict - we don't need index value:
            properties = data[property_name]
        elif isinstance(data, list):
            # data is a list - this has typically just one item, so we use 0 as index
            properties = data[0][property_name]
        else:
            logger.error(
                "Data needs to be a list or dict but it is -> %s", str(type(data))
            )
            return None
        logger.debug(
            "Properties of results (list, index -> %s) -> %s",
            str(index),
            properties,
        )
        if not key in properties:
            if show_error:
                logger.error("Key -> '%s' is not in result properties!", key)
            return None
        return properties[key]
    else:
        logger.error(
            "Result needs to be a list or dict but it is -> %s", str(type(results))
        )
        return None

get_result_values(response, key, property_name='properties', data_name='data')

Read an item value from the REST API response. This is considering the most typical structures delivered by V2 REST API of Extended ECM. See developer.opentext.com for more details.

Parameters:

Name Type Description Default
response dict

REST API response object

required
key str

key to find (e.g. "id", "name", ...)

required
property_name str

name of the sub dictionary holding the actual values. Default is "properties".

'properties'
data_name str

name of the sub dictionary holding the data. Default = "data"

'data'

Returns: str: value of the item with the given key for None if no value is found for the given key.

Source code in pyxecm/otcs.py
def get_result_values(
    self,
    response: dict,
    key: str,
    property_name: str = "properties",
    data_name: str = "data",
) -> list | None:
    """Read an item value from the REST API response. This is considering
       the most typical structures delivered by V2 REST API of Extended ECM.
       See developer.opentext.com for more details.

    Args:
        response (dict): REST API response object
        key (str): key to find (e.g. "id", "name", ...)
        property_name (str, optional): name of the sub dictionary holding the actual values.
                                       Default is "properties".
        data_name (str, optional): name of the sub dictionary holding the data. Default = "data"
    Returns:
        str: value of the item with the given key for None if no value is found for the given key.
    """

    # First do some sanity checks:
    if not response:
        logger.debug("Empty REST response - returning None")
        return None
    if not "results" in response:
        logger.error("No 'results' key in REST response - returning None")
        return None

    results = response["results"]
    if not results:
        logger.debug("No results found!")
        return None

    # check if results is a list or a dict (both is possible - dependent on the actual REST API):
    if isinstance(results, dict):
        # result is a dict - we don't need index value

        # this is a special treatment for the businessworkspaces REST API - it returns
        # for "Create business workspace" the ID directly in the results dict (without data substructure)
        if key in results:
            return [results[key]]
        data = results[data_name]
        if isinstance(data, dict):
            # data is a dict - we don't need index value:
            properties = data[property_name]
        elif isinstance(data, list):
            # data is a list - this has typically just one item, so we use 0 as index
            if property_name:
                properties = data[0][property_name]
                logger.debug("Properties of results (dict) -> %s", str(properties))
            else:
                properties = data
                logger.debug(
                    "Response does not have properties structure. Using data structure directly."
                )
        else:
            logger.error(
                "Data needs to be a list or dict but it is -> %s", str(type(data))
            )
            return None
        # For nearly all OTCS REST Calls properties is a dict:
        if isinstance(properties, dict):
            if not key in properties:
                logger.error("Key -> '%s' is not in result properties!", key)
                return None
            return [properties[key]]
        # but there are some strange ones that have other names for
        # properties and may use a list - see e.g. /v2/holds
        elif isinstance(properties, list):
            return [item[key] for item in properties]
        else:
            logger.error(
                "Properties needs to be a list or dict but it is -> %s",
                str(type(properties)),
            )
            return None
    elif isinstance(results, list):
        return [item[data_name][property_name][key] for item in results]
    else:
        logger.error(
            "Result needs to be a list or dict but it is -> %s", str(type(results))
        )
        return None

get_server_info()

Get Content Server information (server info)

Returns: dict: server information or None if the call fails

Example response:
{
    'mobile': {
        'cs_viewer_support': False,
        'offline_use': True
    },
    'server': {
        'advanced_versioning': True,
        'character_encoding': 1,
        'current_date': '2023-09-05T17:09:41',
        'current_locale_suffix': '_en_US',
        'domain_access_enabled': False,
        'enhanced_advanced_versioning': False,
        'force_download_for_mime_types': [...],
        'language_code': 'USA',
        'languages': [...],
        'metadata_languages: [...],
        'url': 'https://otcs.dev.idea-te.eimdemo.com/cs/cs'
        'version': '23.3'
        ...
    },
    'sessions': {
        'enabled': True,
        'expire_after_last_login': False,
        'expire_after_last_request': True,
        'logout_url': '?func=ll.DoLogout&secureRequestToken=LUAQSY%2BJs4KnlwoVgxLtxQFYrov2XefJQM9ShyhOK93Mzp3ymCxX6IGMTtUgNvTH7AYVt%2BbWLEw%3D',
        'session_inactivity': 7020000,
        'session_reaction_time': 180000,
        'session_timeout': 7200000
    },
    'viewer': {
        'content_suite': {...}
    }
}
Source code in pyxecm/otcs.py
def get_server_info(self) -> dict | None:
    """Get Content Server information (server info)

    Args:
        None
    Returns:
        dict: server information or None if the call fails

        Example response:
        {
            'mobile': {
                'cs_viewer_support': False,
                'offline_use': True
            },
            'server': {
                'advanced_versioning': True,
                'character_encoding': 1,
                'current_date': '2023-09-05T17:09:41',
                'current_locale_suffix': '_en_US',
                'domain_access_enabled': False,
                'enhanced_advanced_versioning': False,
                'force_download_for_mime_types': [...],
                'language_code': 'USA',
                'languages': [...],
                'metadata_languages: [...],
                'url': 'https://otcs.dev.idea-te.eimdemo.com/cs/cs'
                'version': '23.3'
                ...
            },
            'sessions': {
                'enabled': True,
                'expire_after_last_login': False,
                'expire_after_last_request': True,
                'logout_url': '?func=ll.DoLogout&secureRequestToken=LUAQSY%2BJs4KnlwoVgxLtxQFYrov2XefJQM9ShyhOK93Mzp3ymCxX6IGMTtUgNvTH7AYVt%2BbWLEw%3D',
                'session_inactivity': 7020000,
                'session_reaction_time': 180000,
                'session_timeout': 7200000
            },
            'viewer': {
                'content_suite': {...}
            }
        }
    """

    request_url = self.config()["serverInfoUrl"]
    request_header = self._cookie

    logger.debug(
        "Retrieve Extended ECM server information; calling -> %s", request_url
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to retrieve Extended ECM server information",
    )

get_server_version()

Get Content Server version

Returns: str: server version number like 23.4

Source code in pyxecm/otcs.py
def get_server_version(self) -> str | None:
    """Get Content Server version

    Args:
        None
    Returns:
        str: server version number like 23.4
    """

    response = self.get_server_info()
    if not response:
        return None

    server_info = response.get("server")
    if not server_info:
        return None

    return server_info.get("version")

get_subnodes(parent_node_id, filter_node_types=-2, filter_name='', show_hidden=False, limit=100, page=1, fields='properties', metadata=False)

Get a subnodes of a parent node ID.

Parameters:

Name Type Description Default
parent_node_id int

Node Id of the node

required
filter_node_types int

-1 get all containers -2 get all searchable objects (default) -3 get all non-containers

-2
filter_name str

filter nodes for specific name (default = no filter)

''
show_hidden bool

list also hidden items (default = False)

False
limit int

maximum number of results (default = 100)

100
page int

number of result page (default = 1 = 1st page)

1
fields str | list

Which fields to retrieve. This can have a big impact on performance! Possible fields: * "properties" - can further be restricted by adding sub-fields in {...} like "properties{id,name,parent_id,description}" * "categories" * "versions" - can further be restricted by adding ".element(0)" to just get the latest version * "permissions" - canfurther be restricted by adding ".limit(5)" to just get the first 5 permissions fields can either be a string (to select just one field group) or a list of strings to select multiple groups

'properties'
metadata bool

Returns metadata (data type, field length, min/max values, etc.) about data, which will be returned under results.metadata / metadata_map / metadata_order

False

Returns: dict: Subnodes information or None if no node with this parent ID is found. Example:

"results": [
    {
        "data": [
            {
                "columns": [
                    {
                    "data_type": 0,
                    "key": "string",
                    "name": "string",
                    "sort_key": "string"
                    }
                ],
                "properties": [
                    {
                        "advanced_versioning": true,
                        "container": true,
                        "container_size": 0,
                        "create_date": "string",
                        "create_user_id": 0,
                        "description": "string",
                        "description_multilingual": {
                            "en": "string",
                            "de": "string"
                        },
                        "external_create_date": "2019-08-24",
                        "external_identity": "string",
                        "external_identity_type": "string",
                        "external_modify_date": "2019-08-24",
                        "external_source": "string",
                        "favorite": true,
                        "guid": "string",
                        "hidden": true,
                        "icon": "string",
                        "icon_large": "string",
                        "id": 0,
                        "modify_date": "2019-08-24",
                        "modify_user_id": 0,
                        "name": "string",
                        "name_multilingual": {
                            "en": "string",
                            "de": "string"
                        },
                        "owner": "string",
                        "owner_group_id": 0,
                        "owner_user_id": 0,
                        "parent_id": 0,
                        "reserved": true,
                        "reserved_date": "string",
                        "reserved_user_id": 0,
                        "status": 0,
                        "type": 0,
                        "type_name": "string",
                        "versionable": true,
                        "versions_control_advanced": true,
                        "volume_id": 0
                    }
                ]
            }
        ]
    }
]
Source code in pyxecm/otcs.py
def get_subnodes(
    self,
    parent_node_id: int,
    filter_node_types: int = -2,
    filter_name: str = "",
    show_hidden: bool = False,
    limit: int = 100,
    page: int = 1,
    fields: (
        str | list
    ) = "properties",  # per default we just get the most important information
    metadata: bool = False,
) -> dict | None:
    """Get a subnodes of a parent node ID.

    Args:
        parent_node_id (int): Node Id of the node
        filter_node_types (int, optional):
            -1 get all containers
            -2 get all searchable objects (default)
            -3 get all non-containers
        filter_name (str, optional): filter nodes for specific name (default = no filter)
        show_hidden (bool, optional): list also hidden items (default = False)
        limit (int, optional): maximum number of results (default = 100)
        page (int, optional): number of result page (default = 1 = 1st page)
        fields (str | list, optional): Which fields to retrieve. This can have a big impact on performance!
                                        Possible fields:
                                        * "properties" - can further be restricted by adding sub-fields in {...} like "properties{id,name,parent_id,description}"
                                        * "categories"
                                        * "versions" - can further be restricted by adding ".element(0)" to just get the latest version
                                        * "permissions" - canfurther be restricted by adding ".limit(5)" to just get the first 5 permissions
                                        fields can either be a string (to select just one field group) or a list of strings to select multiple groups
        metadata (bool, optional): Returns metadata (data type, field length, min/max values, etc.)
                                   about data, which will be returned under results.metadata /
                                   metadata_map / metadata_order
    Returns:
        dict: Subnodes information or None if no node with this parent ID is found.
        Example:

        "results": [
            {
                "data": [
                    {
                        "columns": [
                            {
                            "data_type": 0,
                            "key": "string",
                            "name": "string",
                            "sort_key": "string"
                            }
                        ],
                        "properties": [
                            {
                                "advanced_versioning": true,
                                "container": true,
                                "container_size": 0,
                                "create_date": "string",
                                "create_user_id": 0,
                                "description": "string",
                                "description_multilingual": {
                                    "en": "string",
                                    "de": "string"
                                },
                                "external_create_date": "2019-08-24",
                                "external_identity": "string",
                                "external_identity_type": "string",
                                "external_modify_date": "2019-08-24",
                                "external_source": "string",
                                "favorite": true,
                                "guid": "string",
                                "hidden": true,
                                "icon": "string",
                                "icon_large": "string",
                                "id": 0,
                                "modify_date": "2019-08-24",
                                "modify_user_id": 0,
                                "name": "string",
                                "name_multilingual": {
                                    "en": "string",
                                    "de": "string"
                                },
                                "owner": "string",
                                "owner_group_id": 0,
                                "owner_user_id": 0,
                                "parent_id": 0,
                                "reserved": true,
                                "reserved_date": "string",
                                "reserved_user_id": 0,
                                "status": 0,
                                "type": 0,
                                "type_name": "string",
                                "versionable": true,
                                "versions_control_advanced": true,
                                "volume_id": 0
                            }
                        ]
                    }
                ]
            }
        ]
    """

    # Add query parameters (these are NOT passed via JSon body!)
    query = {
        "where_type": filter_node_types,
        "limit": limit,
    }
    if filter_name:
        query["where_name"] = filter_name
    if show_hidden:
        query["show_hidden"] = show_hidden
    if page > 1:
        query["page"] = page
    if fields:
        query["fields"] = fields

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(parent_node_id)
        + "/nodes"
        + "?{}".format(encoded_query)
    )

    if metadata:
        request_url += "&metadata"

    request_header = self.request_form_header()

    logger.debug(
        "Get subnodes of parent node with ID -> %s; calling -> %s",
        str(parent_node_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get subnodes for parent node with ID -> {}".format(
            parent_node_id
        ),
    )

get_unique_names(names, subtype=None)

Get definition information for Unique Names.

Parameters:

Name Type Description Default
names list

list of unique names to lookup.

required
subtype int

filter unique names for those pointing to a specific subtype

None

Returns:

Type Description
dict | None

dict | None: Unique name definition information or None if REST call fails.

dict | None

Example response:

dict | None

{ 'links': {'data': {...}}, 'results': [ { 'NodeId': 13653, 'NodeName': 'Functional Location', 'UniqueName': 'ot_templ_func_location' }, { 'NodeId': 2424, 'NodeName': 'Content Server Document Templates', 'UniqueName': 'Document Templates' } ]

dict | None

}

Source code in pyxecm/otcs.py
def get_unique_names(self, names: list, subtype: int | None = None) -> dict | None:
    """Get definition information for Unique Names.

    Args:
        names (list): list of unique names to lookup.
        subtype (int): filter unique names for those pointing to a specific subtype

    Returns:
        dict | None: Unique name definition information or None if REST call fails.

        Example response:
        {
            'links': {'data': {...}},
            'results': [
                {
                    'NodeId': 13653,
                    'NodeName': 'Functional Location',
                    'UniqueName': 'ot_templ_func_location'
                },
                {
                    'NodeId': 2424,
                    'NodeName': 'Content Server Document Templates',
                    'UniqueName': 'Document Templates'
                }
            ]
        }
    """

    if not names:
        logger.error("Missing Unique Names!")
        return None

    # Add query parameters (these are NOT passed via JSon body!)
    query = {"where_names": "{" + ", ".join(names) + "}"}
    if subtype:
        query["where_subtype"] = subtype

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = self.config()["uniqueNamesUrl"] + "?{}".format(encoded_query)
    request_header = self.request_form_header()

    if subtype:
        logger.debug(
            "Get unique names -> %s of subtype -> %s; calling -> %s",
            str(names),
            str(subtype),
            request_url,
        )
        warning_message = (
            "Failed to get unique names -> {} of subtype -> {}".format(
                names, subtype
            )
        )
    else:
        logger.debug(
            "Get unique names -> %s; calling -> %s",
            str(names),
            request_url,
        )
        warning_message = "Failed to get unique names -> {}".format(names)

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        warning_message=warning_message,
        show_error=False,
    )

get_user(name, show_error=False)

Lookup Extended ECM user based on the login name.

Parameters:

Name Type Description Default
name str

name of the user (login)

required
show_error bool

treat as error if user is not found

False

Returns: dict: User information or None if the user is not found. The returned information has a structure like this:

{
    'collection':
    {
        'paging': {...},
        'sorting': {...}
    },
    'links':
    {
        'data': {...}
    },
    'results': [
        {
            'data':
            {
                {
                    'birth_date': None,
                    'business_email': 'pramos@M365x61936377.onmicrosoft.com',
                    'business_fax': None,
                    'business_phone': None,
                    'cell_phone': None,
                    'deleted': False,
                    'display_language': None,
                    'first_name': 'Peter',
                    'gender': None,
                    'group_id': 8006,
                    'home_address_1': None,
                    'home_address_2': None,
                    'home_fax': None,
                    'home_phone': None,
                    'id': 8123,
                    'initials': None,
                    'last_name': 'Ramos',
                    'middle_name': None,
                    'name': 'pramos',
                    'name_formatted': 'Peter Ramos',
                    ...
                    'photo_id': 13981,
                    'photo_url': 'api/v1/members/8123/photo?v=13981.1'
                    ...
                    'type'; 0,
                    'type_name': 'User'
                    }
            }
        }
    ]
}
To access the (login) name of the first user found use ["results"][0]["data"]["properties"]["name"].
It is easier to use the method get_result_value(response, "name", 0)
Source code in pyxecm/otcs.py
def get_user(self, name: str, show_error: bool = False) -> dict | None:
    """Lookup Extended ECM user based on the login name.

    Args:
        name (str): name of the user (login)
        show_error (bool): treat as error if user is not found
    Returns:
        dict: User information or None if the user is not found.
        The returned information has a structure like this:

        {
            'collection':
            {
                'paging': {...},
                'sorting': {...}
            },
            'links':
            {
                'data': {...}
            },
            'results': [
                {
                    'data':
                    {
                        {
                            'birth_date': None,
                            'business_email': 'pramos@M365x61936377.onmicrosoft.com',
                            'business_fax': None,
                            'business_phone': None,
                            'cell_phone': None,
                            'deleted': False,
                            'display_language': None,
                            'first_name': 'Peter',
                            'gender': None,
                            'group_id': 8006,
                            'home_address_1': None,
                            'home_address_2': None,
                            'home_fax': None,
                            'home_phone': None,
                            'id': 8123,
                            'initials': None,
                            'last_name': 'Ramos',
                            'middle_name': None,
                            'name': 'pramos',
                            'name_formatted': 'Peter Ramos',
                            ...
                            'photo_id': 13981,
                            'photo_url': 'api/v1/members/8123/photo?v=13981.1'
                            ...
                            'type'; 0,
                            'type_name': 'User'
                            }
                    }
                }
            ]
        }
        To access the (login) name of the first user found use ["results"][0]["data"]["properties"]["name"].
        It is easier to use the method get_result_value(response, "name", 0)
    """

    # Add query parameters (these are NOT passed via JSon body!)
    # type = 0 ==> User
    query = {"where_type": 0, "where_name": name}
    encoded_query = urllib.parse.urlencode(query, doseq=True)
    request_url = self.config()["membersUrlv2"] + "?{}".format(encoded_query)

    request_header = self.request_form_header()

    logger.debug(
        "Get user with login name -> '%s'; calling -> %s", name, request_url
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get user with login -> '{}'".format(name),
        warning_message="Couldn't find user with login -> '{}'".format(name),
        show_error=show_error,
    )

get_user_profile()

Update a defined field for a user profile. IMPORTANT: this method needs to be called by the authenticated user

Returns: dict: User information or None if the user couldn't be updated (e.g. because it doesn't exist).

Source code in pyxecm/otcs.py
def get_user_profile(self) -> dict | None:
    """Update a defined field for a user profile.
       IMPORTANT: this method needs to be called by the authenticated user

    Args:
        None
    Returns:
        dict: User information or None if the user couldn't be updated
              (e.g. because it doesn't exist).
    """

    request_url = self.config()["membersUrlv2"] + "/preferences"
    request_header = self.request_form_header()

    logger.debug(
        "Get profile (settings) for current user; calling -> %s",
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get profile of current user",
    )

get_user_proxies(use_v2=False)

Get list of user proxies. This method needs to be called as the user the proxy is acting for. Args: None Returns: dict: Node information or None if REST call fails.

Source code in pyxecm/otcs.py
def get_user_proxies(self, use_v2: bool = False) -> dict | None:
    """Get list of user proxies.
       This method needs to be called as the user the proxy is acting for.
    Args:
        None
    Returns:
        dict: Node information or None if REST call fails.
    """

    if use_v2:
        request_url = self.config()["membersUrlv2"] + "/proxies"
    else:
        request_url = self.config()["membersUrl"] + "/proxies"
    request_header = self.request_form_header()

    logger.debug("Get proxy users for current user; calling -> %s", request_url)

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get proxy users for current user",
    )

get_volume(volume_type, timeout=REQUEST_TIMEOUT)

Get Volume information based on the volume type ID.

Parameters:

Name Type Description Default
volume_type int

ID of the volume type

required
timeout int

timeout for the request in seconds

REQUEST_TIMEOUT

Returns: dict: Volume Details or None if volume is not found. ["results"]["data"]["properties"]["id"] is the node ID of the volume.

Source code in pyxecm/otcs.py
def get_volume(
    self, volume_type: int, timeout: int = REQUEST_TIMEOUT
) -> dict | None:
    """Get Volume information based on the volume type ID.

    Args:
        volume_type (int): ID of the volume type
        timeout (int, optional): timeout for the request in seconds
    Returns:
        dict: Volume Details or None if volume is not found.
        ["results"]["data"]["properties"]["id"] is the node ID of the volume.
    """

    request_url = self.config()["volumeUrl"] + "/" + str(volume_type)
    request_header = self.request_form_header()

    logger.debug(
        "Get volume type -> %s; calling -> %s", str(volume_type), request_url
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=timeout,
        failure_message="Failed to get volume of type -> {}".format(volume_type),
    )

get_volumes()

Get all Volumes.

Returns: dict: Volume Details or None if an error occured. { 'links': { 'data': {...} }, 'results': [ { 'data': { 'properties': { 'advanced_versioning': None, 'container': True, 'container_size': 16, 'create_date': '2023-05-07T23:18:50Z', 'create_user_id': 1000, 'description': '', 'description_multilingual': {'de': '', 'en': '', 'fr': '', 'it': '', 'ja': ''}, 'external_create_date': None, 'external_identity': '', 'external_identity_type': '', 'external_modify_date': None, 'external_source': '', 'favorite': False, 'hidden': False, ... 'id': 2000, ... 'name': 'Enterprise', 'name_multilingual': {'de': '', 'en': 'Enterprise', 'fr': '', 'it': '', 'ja': ''}, ... 'parent_id': -1, 'type': 141, 'volume_id': -2000, ... } ... } }, ... ] } Example: ["results"][0]["data"]["properties"]["id"] is the node ID of the volume.

Source code in pyxecm/otcs.py
def get_volumes(self) -> dict | None:
    """Get all Volumes.

    Args:
        None
    Returns:
        dict: Volume Details or None if an error occured.
        {
            'links': {
                'data': {...}
            },
            'results': [
                {
                    'data': {
                        'properties': {
                            'advanced_versioning': None,
                            'container': True,
                            'container_size': 16,
                            'create_date': '2023-05-07T23:18:50Z',
                            'create_user_id': 1000,
                            'description': '',
                            'description_multilingual': {'de': '', 'en': '', 'fr': '', 'it': '', 'ja': ''},
                            'external_create_date': None,
                            'external_identity': '',
                            'external_identity_type': '',
                            'external_modify_date': None,
                            'external_source': '',
                            'favorite': False,
                            'hidden': False,
                            ...
                            'id': 2000,
                            ...
                            'name': 'Enterprise',
                            'name_multilingual': {'de': '', 'en': 'Enterprise', 'fr': '', 'it': '', 'ja': ''},
                            ...
                            'parent_id': -1,
                            'type': 141,
                            'volume_id': -2000,
                            ...
                        }
                        ...
                    }
                },
                ...
            ]
        }
        Example:
        ["results"][0]["data"]["properties"]["id"] is the node ID of the volume.
    """

    request_url = self.config()["volumeUrl"]
    request_header = self.request_form_header()

    logger.debug("Get all volumes; calling -> %s", request_url)

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get volumes",
    )

get_web_report_parameters(nickname)

Get parameters of a Web Report in Extended ECM. These are defined on the Web Report node (Properties --> Parameters)

Parameters:

Name Type Description Default
nickname str

Nickname of the Web Reports node.

required

Returns: Response: List of Web Report parameters. Each list item is a dict describing the parameter. Structure of the list items: { "type": "string", "parm_name": "string", "display_text": "string", "prompt": true, "prompt_order": 0, "default_value": null, "description": "string", "mandatory": true } None if the REST call has failed.

Source code in pyxecm/otcs.py
def get_web_report_parameters(self, nickname: str) -> list | None:
    """Get parameters of a Web Report in Extended ECM. These are defined on the Web Report node
        (Properties --> Parameters)

    Args:
        nickname (str): Nickname of the Web Reports node.
    Returns:
        Response: List of Web Report parameters. Each list item is a dict describing the parameter.
        Structure of the list items:
        {
            "type": "string",
            "parm_name": "string",
            "display_text": "string",
            "prompt": true,
            "prompt_order": 0,
            "default_value": null,
            "description": "string",
            "mandatory": true
        }
        None if the REST call has failed.
    """

    request_url = self.config()["webReportsUrl"] + "/" + nickname + "/parameters"
    request_header = self.request_form_header()

    logger.debug(
        "Get parameters of Web Report with nickname -> '%s'; calling -> %s",
        nickname,
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get parameters of Web Report with nickname -> '{}'".format(
            nickname
        ),
    )

    if response and "data" in response:
        return response["data"]

    return None

get_workflow_attributes(workflow_id, form_prefix='WorkflowForm')

Get workflow attribute definition. It returns a dictionary to allow looking up attribute IDs based on the attribute names.

Parameters:

Name Type Description Default
workflow_id int

Node ID of the workflow.

required

Returns:

Name Type Description
dict | None

dict | None: Keys are the attribute names. Values are the attribute IDs. None in case an error occurs.

Example dict | None
dict | None

{ 'Approval Date': { 'id': '25397_10', 'type': 'Date' 'form_id': 'WorkflowForm_10' }, 'Official': { 'id': '25397_11', 'type': 'Boolean' 'form_id': 'WorkflowForm_11' }, 'Approver': { 'id': '25397_8', 'type': 'Integer' 'form_id': 'WorkflowForm_8' }, 'Status': { 'id': '25397_9', 'type': 'String' 'form_id': 'WorkflowForm_9' }

dict | None

}

Source code in pyxecm/otcs.py
def get_workflow_attributes(
    self, workflow_id: int, form_prefix: str = "WorkflowForm"
) -> dict | None:
    """Get workflow attribute definition. It returns a dictionary
       to allow looking up attribute IDs based on the attribute names.

    Args:
        workflow_id (int): Node ID of the workflow.

    Returns:
        dict | None: Keys are the attribute names. Values are the attribute IDs.
                     None in case an error occurs.

        Example:
        {
            'Approval Date': {
                'id': '25397_10',
                'type': 'Date'
                'form_id': 'WorkflowForm_10'
            },
            'Official': {
                'id': '25397_11',
                'type': 'Boolean'
                'form_id': 'WorkflowForm_11'
            },
            'Approver': {
                'id': '25397_8',
                'type': 'Integer'
                'form_id': 'WorkflowForm_8'
            },
            'Status': {
                'id': '25397_9',
                'type': 'String'
                'form_id': 'WorkflowForm_9'
            }
        }
    """

    response = self.get_workflow_definition(workflow_id=workflow_id)

    if not response or not "results" in response:
        return None

    results = response["results"]
    if not "definition" in results:
        logger.error("Workflow definition is missing 'results' data structure!")
        return None

    # we just need the definition part of the workflow definition:
    definition = results["definition"]

    # in particular we want to lookup a specific data package
    # that includes the attribute definitions:
    if not "data_packages" in definition:
        logger.error("Workflow definition does not have data packages!")
        return None

    # Initialize the result dictionary:
    result = {}

    for data_package in definition["data_packages"]:
        data = data_package.get("data", None)
        if data and "definitions" in data:
            # We found the right data package with the attribute definitions!
            attribute_definitions = data["definitions"]
            for key, value in attribute_definitions.items():
                attribute_type = value.get("type_name", None)
                # the assoc represents the whole data structure
                # and is not a single attribute - we skip it:
                if attribute_type == "Assoc":
                    continue
                # We construct the dict in a way that allows
                # to lookup attribute IDs based on attribute names.
                # we also add a key with the 'form_prefix' as the
                # draft process needs it in that syntax.
                form_id = form_prefix + "_" + key.split("_")[1]
                result[value.get("name")] = {
                    "id": key,
                    "type": attribute_type,
                    "form_id": form_id,
                }

    return result

get_workflow_definition(workflow_id)

Get the workflow definition.

Parameters:

Name Type Description Default
workflow_id int

node ID of the workflow item (map)

required

Returns:

Name Type Description
dict | None

dict | None: workflow definition data

Example dict | None
dict | None

{ 'links': { 'data': {...} }, 'results': { 'definition': { 'data_packages': [ { 'data': {}, 'description': None, 'sub_type': 2, 'type': 1 }, { 'data': { 'data': { 'data': { '25397_10': None, '25397_11': False, '25397_8': None, '25397_9': None }, 'definitions': { '25397': {...}, '25397_10': { 'allow_undefined': False, 'bulk_shared': False, 'default_value': None, 'description': None, 'hidden': False, 'include_time': False, 'key': '25397_10', 'key_value_pairs': False, 'multi_value': False, 'multi_value_length_default': 1, 'multi_value_length_fixed': True, 'multi_value_length_max': 1, 'multi_value_max_length': None, 'multi_value_min_length': None, 'multi_value_unique': False, 'name': 'Approval Date', 'persona': '', 'read_only': False, 'required': False, 'type': -7, 'type_llattribute': -7, 'type_name': 'Date', 'valid_values': [], 'valid_values_name': [] }, '25397_11': {...}, '25397_8': {...}, '25397_9': {...} }, 'definitions_map': { '25397': [...] }, 'definitions_order': ['25397'] }, 'definitions': {...}, 'definitions_map': {...}, 'definitions_order': [...] }, 'description': 'Please fill in all required attributes.', 'sub_type': 3, 'type': 1 }, {...}, {...} ], 'tasks': [ {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...} ], 'workflow_id': 25397, 'workflow_roles': [] } }

dict | None

}

Source code in pyxecm/otcs.py
def get_workflow_definition(self, workflow_id: int) -> dict | None:
    """Get the workflow definition.

    Args:
        workflow_id (int): node ID of the workflow item (map)

    Returns:
        dict | None: workflow definition data

        Example:
        {
            'links': {
                'data': {...}
            },
            'results': {
                'definition': {
                    'data_packages': [
                        {
                            'data': {},
                            'description': None,
                            'sub_type': 2,
                            'type': 1
                        },
                        {
                            'data': {
                                'data': {
                                    'data': {
                                        '25397_10': None,
                                        '25397_11': False,
                                        '25397_8': None,
                                        '25397_9': None
                                    },
                                    'definitions': {
                                        '25397': {...},
                                        '25397_10': {
                                            'allow_undefined': False,
                                            'bulk_shared': False,
                                            'default_value': None,
                                            'description': None,
                                            'hidden': False,
                                            'include_time': False,
                                            'key': '25397_10',
                                            'key_value_pairs': False,
                                            'multi_value': False,
                                            'multi_value_length_default': 1,
                                            'multi_value_length_fixed': True,
                                            'multi_value_length_max': 1,
                                            'multi_value_max_length': None,
                                            'multi_value_min_length': None,
                                            'multi_value_unique': False,
                                            'name': 'Approval Date',
                                            'persona': '',
                                            'read_only': False,
                                            'required': False,
                                            'type': -7,
                                            'type_llattribute': -7,
                                            'type_name': 'Date',
                                            'valid_values': [],
                                            'valid_values_name': []
                                        },
                                        '25397_11': {...},
                                        '25397_8': {...},
                                        '25397_9': {...}
                                    },
                                    'definitions_map': {
                                        '25397': [...]
                                    },
                                    'definitions_order': ['25397']
                                },
                                'definitions': {...},
                                'definitions_map': {...},
                                'definitions_order': [...]
                            },
                            'description': 'Please fill in all required attributes.',
                            'sub_type': 3,
                            'type': 1
                        },
                        {...},
                        {...}
                    ],
                    'tasks': [
                        {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}
                    ],
                    'workflow_id': 25397,
                    'workflow_roles': []
                }
            }
        }
    """

    request_url = (
        self.config()["workflowUrl"] + "/" + str(workflow_id) + "/definition"
    )
    request_header = self.request_form_header()

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get definition of workflow with ID -> {}".format(
            workflow_id
        ),
    )

get_workflow_status(process_id)

Get the status (task list) of a workflow instance (process)

Parameters:

Name Type Description Default
process_id int

ID of the process (worflow instance)

required

Returns:

Type Description
dict | None

dict | None: Task list of the workflow instance or None if the request fails.

dict | None

Example result:

dict | None

{ 'links': { 'data': { 'self': { 'body': '', 'content_type': '', 'href': '/api/v2/workflows/status/processes/159324', 'method': 'GET', 'name': '' } } }, 'results': { 'attachments': {'attachment_folder_id': 159311}, 'data_packages': [ { 'TYPE': 1, 'SUBTYPE': 1, 'USERDATA': 159311, 'DESCRIPTION': '' }, { 'TYPE': 1, 'SUBTYPE': 2, 'USERDATA': 159314, 'DESCRIPTION': '' }, { 'TYPE': 1, 'SUBTYPE': 3, 'USERDATA': {...}, 'DESCRIPTION': 'Please fill in all required attributes.' } ], 'permissions': { 'Archive': True, 'ChangeAttr': True, 'ChangeRoute': True, 'Delete': True, 'ManagerPerms': True, 'SeeDetail': True, 'Stop': True, 'Suspend': True }, 'step_list': { 'completed': [], 'current': [ { 'process_id': 159314, 'subprocess_id': 159314, 'task_id': 10, 'task_name': 'set Item Status = pending approval', 'task_due_date': '', 'task_start_date': '2024-10-03T15:21:23', 'task_status': 'ontime', 'task_assignees': { 'assignee': [ { 'userId': 1000, 'loginName': 'Admin', 'firstName': '', 'lastName': '', 'emailAddress': '', 'phone': '' } ], 'assigneeCount': 1, 'currentAssignee': ' ' } } ], 'next': [] }, 'wf_details': { 'date_initiated': '2024-10-03T15:21:23', 'due_date': '', 'initiator': { 'firstName': 'Paul', 'lastName': 'Williams', 'loginName': 'pwilliams', 'userId': 15235 }, 'status': 'ontime', 'wf_name': 'Test without due date', 'work_workID': 159314 } }

dict | None

}

Source code in pyxecm/otcs.py
def get_workflow_status(self, process_id: int) -> dict | None:
    """Get the status (task list) of a workflow instance (process)

    Args:
        process_id (int): ID of the process (worflow instance)

    Returns:
        dict | None: Task list of the workflow instance or None if the request fails.

        Example result:
        {
            'links': {
                'data': {
                    'self': {
                        'body': '',
                        'content_type': '',
                        'href': '/api/v2/workflows/status/processes/159324',
                        'method': 'GET',
                        'name': ''
                    }
                }
            },
            'results': {
                'attachments': {'attachment_folder_id': 159311},
                'data_packages': [
                    {
                        'TYPE': 1,
                        'SUBTYPE': 1,
                        'USERDATA': 159311,
                        'DESCRIPTION': ''
                    },
                    {
                        'TYPE': 1,
                        'SUBTYPE': 2,
                        'USERDATA': 159314,
                        'DESCRIPTION': ''
                    },
                    {
                        'TYPE': 1,
                        'SUBTYPE': 3,
                        'USERDATA': {...},
                        'DESCRIPTION': 'Please fill in all required attributes.'
                    }
                ],
                'permissions': {
                    'Archive': True,
                    'ChangeAttr': True,
                    'ChangeRoute': True,
                    'Delete': True,
                    'ManagerPerms': True,
                    'SeeDetail': True,
                    'Stop': True,
                    'Suspend': True
                },
                'step_list': {
                    'completed': [],
                    'current': [
                        {
                            'process_id': 159314,
                            'subprocess_id': 159314,
                            'task_id': 10,
                            'task_name': 'set Item Status = pending approval',
                            'task_due_date': '',
                            'task_start_date': '2024-10-03T15:21:23',
                            'task_status': 'ontime',
                            'task_assignees': {
                                'assignee': [
                                    {
                                        'userId': 1000,
                                        'loginName': 'Admin',
                                        'firstName': '',
                                        'lastName': '',
                                        'emailAddress': '',
                                        'phone': ''
                                    }
                                ],
                                'assigneeCount': 1,
                                'currentAssignee': ' '
                            }
                        }
                    ],
                    'next': []
                },
                'wf_details': {
                    'date_initiated': '2024-10-03T15:21:23',
                    'due_date': '',
                    'initiator': {
                        'firstName': 'Paul',
                        'lastName': 'Williams',
                        'loginName': 'pwilliams',
                        'userId': 15235
                    },
                    'status': 'ontime',
                    'wf_name': 'Test without due date',
                    'work_workID': 159314
                }
            }
        }
    """

    request_url = self.config()["workflowUrl"] + "/status/processes/{}".format(
        process_id
    )
    request_header = self.request_form_header()

    logger.debug(
        "Get workflow status (task list) of process ID -> %s; calling -> %s",
        str(process_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get workflow status for process ID -> {}".format(
            process_id
        ),
    )

get_workflows_by_kind_and_status(kind=None, status=None, sort=None)

Get a list of workflows with a defined kind and status. This method is personlalized, you need to call it with the user thse workflows are related to

Parameters:

Name Type Description Default
kind str | None

"Managed", "Initiated", "Both". Defaults to None.

None
status str | None

"ontime", "workflowlate", "stopped", "completed". Defaults to None (=all).

None
sort str | None

Sorting order, like "name asc", "name desc", "data_initiated asc", "status_key desc". Defaults to None.

None

Returns:

Name Type Description
list list

list of matching workflows

Example list
list

{ "links": { "data": { "self": { "body": "", "content_type": "", "href": "/api/v2/workflows/status", "method": "GET", "name": "" } } }, "results": [ { "data": { "wfstatus": { "assignee": [ { "userId": 15665, "loginName": "dfoxhoven", "firstName": "Deke", "lastName": "Foxhoven", "emailAddress": "dfoxhoven@dev.idea-te.eimdemo.com", "phone": "" } ], "assignee_count": 1, "comments_on": true, "current_assignee": "Deke Foxhoven", "date_initiated": "2024-09-27T15:50:47", "due_date": "", "parallel_steps": [ { "process_id": 160580, "subprocess_id": 160580, "task_id": 1, "task_name": "Approver", "task_due_date": "", "task_start_date": "2024-09-27T15:51:13", "task_status": "ontime", "task_assignees": { "assignee": [ { "userId": 15665, "loginName": "dfoxhoven", "firstName": "Deke", "lastName": "Foxhoven", "emailAddress": "dfoxhoven@dev.idea-te.eimdemo.com", "phone": "" } ], "assigneeCount": 1, "currentAssignee": "Deke Foxhoven" } } ], "process_id": 160580, "status_key": "ontime", "step_name": "Approver", "steps_count": 1, "subprocess_id": 160580, "task_id": 1, "wf_name": "Contract Approval Workflow (1 step)" } }, "definitions": { "wfstatus": { "assignee": { "allow_undefined": false, "bulk_shared": false, "default_value": null, "description": null, "hidden": false, "key": "assignee", "max_value": null, "min_value": null, "multi_value": false, "name": "Assigned to", "persona": "", "read_only": true, "required": false, "type": 2, "type_name": "Integer", "valid_values": [], "valid_values_name": [] }, "date_initiated": { "allow_undefined": false, "bulk_shared": false, "default_value": null, "description": null, "hidden": false, "include_time": true, "key": "date_initiated", "multi_value": false, "name": "Start Date", "persona": "", "read_only": true, "required": false, "type": -7, "type_name": "Date", "valid_values": [], "valid_values_name": [] }, "due_date": { "allow_undefined": false, "bulk_shared": false, "default_value": null, "description": null, "hidden": false, "include_time": true, "key": "due_date", "multi_value": false, "name": "Step Due Date", "persona": "", "read_only": true, "required": false, "type": -7, "type_name": "Date", "valid_values": [], "valid_values_name": [] }, "status_key": { "allow_undefined": false, "bulk_shared": false, "default_value": null, "description": null, "hidden": false, "key": "status_key", "max_length": null, "min_length": null, "multi_value": false, "multiline": false, "multilingual": false, "name": "Status", "password": false, "persona": "", "read_only": true, "regex": "", "required": false, "type": -1, "type_name": "String", "valid_values": [], "valid_values_name": [] }, "step_name": { "allow_undefined": false, "bulk_shared": false, "default_value": null, "description": null, "hidden": false, "key": "step_name", "max_length": null, "min_length": null, "multi_value": false, "multiline": false, "multilingual": true, "name": "Current Step", "password": false, "persona": "", "read_only": true, "regex": "", "required": false, "type": -1, "type_name": "String", "valid_values": [], "valid_values_name": [] }, "wf_name": { "allow_undefined": false, "bulk_shared": false, "default_value": null, "description": null, "hidden": false, "key": "wf_name", "max_length": null, "min_length": null, "multi_value": false, "multiline": false, "multilingual": true, "name": "Workflow", "password": false, "persona": "", "read_only": true, "regex": "", "required": false, "type": -1, "type_name": "String", "valid_values": [], "valid_values_name": [] } } }, "definitions_map": { "wfstatus": {} }, "definitions_order": { "wfstatus": [ "status_key", "due_date", "wf_name", "step_name", "assignee", "date_initiated" ] }, "permissions": { "Archive": true, "ChangeAttr": true, "ChangeRoute": true, "Delete": true, "ManagerPerms": true, "SeeDetail": true, "Stop": true, "Suspend": true } } ]

list

}

Source code in pyxecm/otcs.py
def get_workflows_by_kind_and_status(
    self,
    kind: str | None = None,
    status: str | list | None = None,
    sort: str | None = None,
) -> list:
    """Get a list of workflows with a defined kind and status. This method is personlalized, you
       need to call it with the user thse workflows are related to

    Args:
        kind (str | None, optional): "Managed", "Initiated", "Both". Defaults to None.
        status (str | None, optional): "ontime", "workflowlate", "stopped", "completed". Defaults to None (=all).
        sort (str | None, optional): Sorting order, like "name asc", "name desc", "data_initiated asc", "status_key desc".
                                     Defaults to None.

    Returns:
        list: list of matching workflows

        Example:
        {
            "links": {
                "data": {
                    "self": {
                        "body": "",
                        "content_type": "",
                        "href": "/api/v2/workflows/status",
                        "method": "GET",
                        "name": ""
                    }
                }
            },
            "results": [
                {
                    "data": {
                        "wfstatus": {
                            "assignee": [
                                {
                                    "userId": 15665,
                                    "loginName": "dfoxhoven",
                                    "firstName": "Deke",
                                    "lastName": "Foxhoven",
                                    "emailAddress": "dfoxhoven@dev.idea-te.eimdemo.com",
                                    "phone": ""
                                }
                            ],
                            "assignee_count": 1,
                            "comments_on": true,
                            "current_assignee": "Deke Foxhoven",
                            "date_initiated": "2024-09-27T15:50:47",
                            "due_date": "",
                            "parallel_steps": [
                                {
                                    "process_id": 160580,
                                    "subprocess_id": 160580,
                                    "task_id": 1,
                                    "task_name": "Approver",
                                    "task_due_date": "",
                                    "task_start_date": "2024-09-27T15:51:13",
                                    "task_status": "ontime",
                                    "task_assignees": {
                                        "assignee": [
                                            {
                                                "userId": 15665,
                                                "loginName": "dfoxhoven",
                                                "firstName": "Deke",
                                                "lastName": "Foxhoven",
                                                "emailAddress": "dfoxhoven@dev.idea-te.eimdemo.com",
                                                "phone": ""
                                            }
                                        ],
                                        "assigneeCount": 1,
                                        "currentAssignee": "Deke Foxhoven"
                                    }
                                }
                            ],
                            "process_id": 160580,
                            "status_key": "ontime",
                            "step_name": "Approver",
                            "steps_count": 1,
                            "subprocess_id": 160580,
                            "task_id": 1,
                            "wf_name": "Contract Approval Workflow (1 step)"
                        }
                    },
                    "definitions": {
                        "wfstatus": {
                            "assignee": {
                                "allow_undefined": false,
                                "bulk_shared": false,
                                "default_value": null,
                                "description": null,
                                "hidden": false,
                                "key": "assignee",
                                "max_value": null,
                                "min_value": null,
                                "multi_value": false,
                                "name": "Assigned to",
                                "persona": "",
                                "read_only": true,
                                "required": false,
                                "type": 2,
                                "type_name": "Integer",
                                "valid_values": [],
                                "valid_values_name": []
                            },
                            "date_initiated": {
                                "allow_undefined": false,
                                "bulk_shared": false,
                                "default_value": null,
                                "description": null,
                                "hidden": false,
                                "include_time": true,
                                "key": "date_initiated",
                                "multi_value": false,
                                "name": "Start Date",
                                "persona": "",
                                "read_only": true,
                                "required": false,
                                "type": -7,
                                "type_name": "Date",
                                "valid_values": [],
                                "valid_values_name": []
                            },
                            "due_date": {
                                "allow_undefined": false,
                                "bulk_shared": false,
                                "default_value": null,
                                "description": null,
                                "hidden": false,
                                "include_time": true,
                                "key": "due_date",
                                "multi_value": false,
                                "name": "Step Due Date",
                                "persona": "",
                                "read_only": true,
                                "required": false,
                                "type": -7,
                                "type_name": "Date",
                                "valid_values": [],
                                "valid_values_name": []
                            },
                            "status_key": {
                                "allow_undefined": false,
                                "bulk_shared": false,
                                "default_value": null,
                                "description": null,
                                "hidden": false,
                                "key": "status_key",
                                "max_length": null,
                                "min_length": null,
                                "multi_value": false,
                                "multiline": false,
                                "multilingual": false,
                                "name": "Status",
                                "password": false,
                                "persona": "",
                                "read_only": true,
                                "regex": "",
                                "required": false,
                                "type": -1,
                                "type_name": "String",
                                "valid_values": [],
                                "valid_values_name": []
                            },
                            "step_name": {
                                "allow_undefined": false,
                                "bulk_shared": false,
                                "default_value": null,
                                "description": null,
                                "hidden": false,
                                "key": "step_name",
                                "max_length": null,
                                "min_length": null,
                                "multi_value": false,
                                "multiline": false,
                                "multilingual": true,
                                "name": "Current Step",
                                "password": false,
                                "persona": "",
                                "read_only": true,
                                "regex": "",
                                "required": false,
                                "type": -1,
                                "type_name": "String",
                                "valid_values": [],
                                "valid_values_name": []
                            },
                            "wf_name": {
                                "allow_undefined": false,
                                "bulk_shared": false,
                                "default_value": null,
                                "description": null,
                                "hidden": false,
                                "key": "wf_name",
                                "max_length": null,
                                "min_length": null,
                                "multi_value": false,
                                "multiline": false,
                                "multilingual": true,
                                "name": "Workflow",
                                "password": false,
                                "persona": "",
                                "read_only": true,
                                "regex": "",
                                "required": false,
                                "type": -1,
                                "type_name": "String",
                                "valid_values": [],
                                "valid_values_name": []
                            }
                        }
                    },
                    "definitions_map": {
                        "wfstatus": {}
                    },
                    "definitions_order": {
                        "wfstatus": [
                            "status_key",
                            "due_date",
                            "wf_name",
                            "step_name",
                            "assignee",
                            "date_initiated"
                        ]
                    },
                    "permissions": {
                        "Archive": true,
                        "ChangeAttr": true,
                        "ChangeRoute": true,
                        "Delete": true,
                        "ManagerPerms": true,
                        "SeeDetail": true,
                        "Stop": true,
                        "Suspend": true
                    }
                }
            ]
        }
    """

    query = {}
    if kind:
        query["kind"] = kind
    if status:
        query["wstatus"] = status
    if sort:
        query["sort"] = sort
    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = self.config()["workflowUrl"] + "/status?{}".format(encoded_query)
    request_header = self.request_form_header()

    logger.debug(
        "Get workflows of kind -> '%s' and status -> '%s'; calling -> %s",
        kind,
        str(status),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get workflows of kind -> {} and status -> {}".format(
            kind, str(status)
        ),
    )

get_workspace(node_id)

Get a workspace based on the node ID.

Parameters:

Name Type Description Default
node_id int

Node ID of the workspace to retrieve.

required

Returns: dict: Workspace node information or None if no node with this ID is found.

Example response:
{
    'links': {
        'data': {...}
    },
    'meta_data': {
        'properties': {...}
    },
    'paging': {
        'limit': 500,
        'page': 1,
        'page_total': 1,
        'range_max': 1,
        'range_min': 1,
        'total_count': 1
    },
    'results': [
        {
            'actions': {...},
            'data': {
                'business_properties': {
                    'business_object_id': '000004000240',
                    'business_object_type': 'BUS2007',
                    'business_object_type_id': 18,
                    'business_object_type_name': 'Maintenance Order',
                    'business_object_type_name_multilingual': {...},
                    'display_url': "https://fiori.qa.idea-te.eimdemo.com:8443/sap/bc/ui2/flp#MaintenanceOrder-displayXecmFactSheet&//C_ObjPgMaintOrder('000004000240')",
                    'external_system_id': 'TM6',
                    'external_system_name': 'TM6',
                    'has_default_display': True,
                    'has_default_search': True,
                    'isEarly': False,
                    'workspace_type_id': 42,
                    'workspace_type_name': 'Maintenance Order',
                    'workspace_type_name_multilingual': {},
                    ...
                }
                'properties': {
                    'volume_id': -2000,
                    'id': 36780,
                    'parent_id': 13567,
                    'owner_user_id': 7240,
                    'name': '4600000044 - C.E.B. New York Inc.',
                    'type': 848,
                    'description': '',
                    'create_date': '2023-09-02T11:07:06',
                    'create_user_id': 7240,
                    'create_user_id': 7240,
                    'modify_date': '2023-09-02T11:07:11',
                    'modify_user_id': 7240,
                    'reserved': False,
                    'reserved_user_id': 0,
                    'reserved_date': None,
                    'order': None,
                    'icon': '/cssupport/otsapxecm/wksp_contract_vendor.png',
                    'hidden': False,
                    'mime_type': None,
                    'original_id': 0,
                    'wnf_wksp_type_id': 16,
                    'wnf_wksp_template_id': 15615,
                    'size_formatted': '7 Items',
                    'type_name': 'Business Workspace',
                    'container': True,
                    'size': 7,
                    ...
                }
                'wksp_info':
                {
                    'wksp_type_icon': '/appimg/ot_bws/icons/16634%2Esvg?v=161194_13949'
                }
            },
            'metadata': {...},
            'metadata_order': {
                'categories': ['16878']
            }
        }
    ],
    'wksp_info': {
        'wksp_type_icon': None
    }
    'workspace_references': [
        {
            'business_object_id': '000004000240',
            'business_object_type': 'BUS2007',
            'business_object_type_id': 18,
            'external_system_id': 'TM6',
            'has_default_display': True,
            'has_default_search': True,
            'workspace_type_id': 42
        }
    ]
}
Source code in pyxecm/otcs.py
def get_workspace(self, node_id: int) -> dict | None:
    """Get a workspace based on the node ID.

    Args:
        node_id (int): Node ID of the workspace to retrieve.
    Returns:
        dict: Workspace node information or None if no node with this ID is found.

        Example response:
        {
            'links': {
                'data': {...}
            },
            'meta_data': {
                'properties': {...}
            },
            'paging': {
                'limit': 500,
                'page': 1,
                'page_total': 1,
                'range_max': 1,
                'range_min': 1,
                'total_count': 1
            },
            'results': [
                {
                    'actions': {...},
                    'data': {
                        'business_properties': {
                            'business_object_id': '000004000240',
                            'business_object_type': 'BUS2007',
                            'business_object_type_id': 18,
                            'business_object_type_name': 'Maintenance Order',
                            'business_object_type_name_multilingual': {...},
                            'display_url': "https://fiori.qa.idea-te.eimdemo.com:8443/sap/bc/ui2/flp#MaintenanceOrder-displayXecmFactSheet&//C_ObjPgMaintOrder('000004000240')",
                            'external_system_id': 'TM6',
                            'external_system_name': 'TM6',
                            'has_default_display': True,
                            'has_default_search': True,
                            'isEarly': False,
                            'workspace_type_id': 42,
                            'workspace_type_name': 'Maintenance Order',
                            'workspace_type_name_multilingual': {},
                            ...
                        }
                        'properties': {
                            'volume_id': -2000,
                            'id': 36780,
                            'parent_id': 13567,
                            'owner_user_id': 7240,
                            'name': '4600000044 - C.E.B. New York Inc.',
                            'type': 848,
                            'description': '',
                            'create_date': '2023-09-02T11:07:06',
                            'create_user_id': 7240,
                            'create_user_id': 7240,
                            'modify_date': '2023-09-02T11:07:11',
                            'modify_user_id': 7240,
                            'reserved': False,
                            'reserved_user_id': 0,
                            'reserved_date': None,
                            'order': None,
                            'icon': '/cssupport/otsapxecm/wksp_contract_vendor.png',
                            'hidden': False,
                            'mime_type': None,
                            'original_id': 0,
                            'wnf_wksp_type_id': 16,
                            'wnf_wksp_template_id': 15615,
                            'size_formatted': '7 Items',
                            'type_name': 'Business Workspace',
                            'container': True,
                            'size': 7,
                            ...
                        }
                        'wksp_info':
                        {
                            'wksp_type_icon': '/appimg/ot_bws/icons/16634%2Esvg?v=161194_13949'
                        }
                    },
                    'metadata': {...},
                    'metadata_order': {
                        'categories': ['16878']
                    }
                }
            ],
            'wksp_info': {
                'wksp_type_icon': None
            }
            'workspace_references': [
                {
                    'business_object_id': '000004000240',
                    'business_object_type': 'BUS2007',
                    'business_object_type_id': 18,
                    'external_system_id': 'TM6',
                    'has_default_display': True,
                    'has_default_search': True,
                    'workspace_type_id': 42
                }
            ]
        }
    """

    request_url = self.config()["businessWorkspacesUrl"] + "/" + str(node_id)
    request_header = self.request_form_header()

    logger.debug(
        "Get workspace with ID -> %s; calling -> %s", str(node_id), request_url
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get workspace with ID -> {}".format(node_id),
    )

get_workspace_by_business_object(external_system_name, business_object_type, business_object_id, return_workspace_metadata=False, show_error=False)

Get a workspace based on the business object of an external system.

Parameters:

Name Type Description Default
external_system_name str

Name of the connection

required
business_object_type str

Type of the Business object, e.g. KNA1 for SAP customers

required
business_object_id str

ID of the business object in the external system

required
return_workspace_metadata bool

Whether or not workspace metadata (categories) should be returned. Default is False.

False
show_error bool

Treat as error if node is not found. Default is False.

False

Returns: dict: Workspace node information or None if no node with this ID is found.

Example response:
{
    'links': {
        'data': {...}
    },
    'meta_data': {
        'properties': {...}
    },
    'paging': {
        'limit': 500,
        'page': 1,
        'page_total': 1,
        'range_max': 1,
        'range_min': 1,
        'total_count': 1
    },
    'results': [
        {
            'actions': {...},
            'data': {
                'properties': {
                    'volume_id': -2000,
                    'id': 36780,
                    'parent_id': 13567,
                    'owner_user_id': 7240,
                    'name': '4600000044 - C.E.B. New York Inc.',
                    'type': 848,
                    'description': '',
                    'create_date': '2023-09-02T11:07:06',
                    'create_user_id': 7240,
                    'create_user_id': 7240,
                    'modify_date': '2023-09-02T11:07:11',
                    'modify_user_id': 7240,
                    'reserved': False,
                    'reserved_user_id': 0,
                    'reserved_date': None,
                    'order': None,
                    'icon': '/cssupport/otsapxecm/wksp_contract_vendor.png',
                    'hidden': False,
                    'mime_type': None,
                    'original_id': 0,
                    'wnf_wksp_type_id': 16,
                    'wnf_wksp_template_id': 15615,
                    'size_formatted': '7 Items',
                    'type_name': 'Business Workspace',
                    'container': True,
                    'size': 7,
                    ...
                }
            },
            'metadata': {...},
            'metadata_order': {...}
        }
    ],
    'wksp_info': {
        'wksp_type_icon': None
    }
}
Source code in pyxecm/otcs.py
def get_workspace_by_business_object(
    self,
    external_system_name: str,
    business_object_type: str,
    business_object_id: str,
    return_workspace_metadata: bool = False,
    show_error: bool = False,
) -> dict | None:
    """Get a workspace based on the business object of an external system.

    Args:
        external_system_name (str): Name of the connection
        business_object_type (str): Type of the Business object, e.g. KNA1 for SAP customers
        business_object_id (str): ID of the business object in the external system
        return_workspace_metadata (bool, optional): Whether or not workspace metadata (categories) should be returned.
                                                    Default is False.
        show_error (bool, optional): Treat as error if node is not found. Default is False.
    Returns:
        dict: Workspace node information or None if no node with this ID is found.

        Example response:
        {
            'links': {
                'data': {...}
            },
            'meta_data': {
                'properties': {...}
            },
            'paging': {
                'limit': 500,
                'page': 1,
                'page_total': 1,
                'range_max': 1,
                'range_min': 1,
                'total_count': 1
            },
            'results': [
                {
                    'actions': {...},
                    'data': {
                        'properties': {
                            'volume_id': -2000,
                            'id': 36780,
                            'parent_id': 13567,
                            'owner_user_id': 7240,
                            'name': '4600000044 - C.E.B. New York Inc.',
                            'type': 848,
                            'description': '',
                            'create_date': '2023-09-02T11:07:06',
                            'create_user_id': 7240,
                            'create_user_id': 7240,
                            'modify_date': '2023-09-02T11:07:11',
                            'modify_user_id': 7240,
                            'reserved': False,
                            'reserved_user_id': 0,
                            'reserved_date': None,
                            'order': None,
                            'icon': '/cssupport/otsapxecm/wksp_contract_vendor.png',
                            'hidden': False,
                            'mime_type': None,
                            'original_id': 0,
                            'wnf_wksp_type_id': 16,
                            'wnf_wksp_template_id': 15615,
                            'size_formatted': '7 Items',
                            'type_name': 'Business Workspace',
                            'container': True,
                            'size': 7,
                            ...
                        }
                    },
                    'metadata': {...},
                    'metadata_order': {...}
                }
            ],
            'wksp_info': {
                'wksp_type_icon': None
            }
        }
    """

    request_url = (
        self.config()["externalSystemUrl"]
        + "/"
        + external_system_name
        + "/botypes/"
        + business_object_type
        + "/boids/"
        + business_object_id
    )
    if return_workspace_metadata:
        request_url += "?metadata"

    request_header = self.request_form_header()

    logger.debug(
        "Get workspace via external system -> '%s' (Business Object Type -> '%s'; Business Object ID -> %s); calling -> %s",
        external_system_name,
        business_object_type,
        business_object_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        warning_message="Cannot get workspace via external system -> '{}', Business Object Type -> '{}', and Business Object ID -> {}. It does not exist.".format(
            external_system_name, business_object_type, business_object_id
        ),
        failure_message="Failed to get workspace via external system -> '{}', Business Object Type -> '{}', and Business Object ID -> {}".format(
            external_system_name, business_object_type, business_object_id
        ),
        show_error=show_error,
    )

get_workspace_by_type_and_name(type_name='', type_id=None, name='', expanded_view=True, page=None, limit=None, timeout=REQUEST_TIMEOUT)

Lookup workspace based on workspace type and workspace name.

Parameters:

Name Type Description Default
type_name str

name of the workspace type

''
type_id int

ID of the workspace_type

None
name str

Name of the workspace, if "" then deliver all instances of the given workspace type.

''
expanded_view bool

If 'False' then just search in recently accessed business workspace for this name and type. If 'True' (this is the default) then search in all workspaces for this name and type.

True
timeout int

timeout for the request in seconds

REQUEST_TIMEOUT

Returns: dict: Workspace information or None if the workspace is not found.

Source code in pyxecm/otcs.py
def get_workspace_by_type_and_name(
    self,
    type_name: str = "",
    type_id: int = None,
    name: str = "",
    expanded_view: bool = True,
    page: int | None = None,
    limit: int | None = None,
    timeout: int = REQUEST_TIMEOUT,
) -> dict | None:
    """Lookup workspace based on workspace type and workspace name.

    Args:
        type_name (str, optional): name of the workspace type
        type_id (int, optional): ID of the workspace_type
        name (str, optional): Name of the workspace, if "" then deliver all instances
                              of the given workspace type.
        expanded_view (bool, optional): If 'False' then just search in recently
                                        accessed business workspace for this name and type.
                                        If 'True' (this is the default) then search in all
                                        workspaces for this name and type.
        timeout (int, optional): timeout for the request in seconds
    Returns:
        dict: Workspace information or None if the workspace is not found.
    """

    if not type_name and not type_id:
        logger.error(
            "No workspace type specified - neither by type name nor type ID. Cannot lookup workspace(s)!"
        )
        return None

    # Add query parameters (these are NOT passed via JSon body!)
    query = {
        "expanded_view": expanded_view,
    }
    if type_name:
        query["where_workspace_type_name"] = type_name
    if type_id:
        query["where_workspace_type_id"] = type_id
    if name:
        query["where_name"] = name
    if page and limit:
        query["page"] = page
        query["limit"] = limit

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = self.config()["businessWorkspacesUrl"] + "?{}".format(
        encoded_query
    )
    request_header = self.request_form_header()

    if name:
        logger.debug(
            "Get workspace with name -> '%s' and type -> '%s'; calling -> %s",
            name,
            type_name,
            request_url,
        )
        failure_message = (
            "Failed to get workspace with name -> '{}' and type -> '{}'".format(
                name, type_name
            )
        )
    else:
        if type_name:
            logger.debug(
                "Get all workspace instances of type -> '%s'; calling -> %s",
                type_name,
                request_url,
            )
            failure_message = (
                "Failed to get all workspace instances of type -> '{}'".format(
                    type_name
                )
            )
        else:
            logger.debug(
                "Get all workspace instances with type ID -> %s; calling -> %s",
                str(type_id),
                request_url,
            )
            failure_message = (
                "Failed to get all workspace instances with type ID -> {}".format(
                    type_id
                )
            )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=timeout,
        failure_message=failure_message,
    )

get_workspace_create_form(template_id, external_system_id=None, bo_type=None, bo_id=None, parent_id=None)

Get the Workspace create form.

Parameters:

Name Type Description Default
template_id int

ID of the workspace template

required
external_system_id str

Identifier of the external system (None if no external system)

None
bo_type str

Business object type (None if no external system)

None
bo_id str

Business object identifier / key (None if no external system)

None
parent_id int

Parent ID of the workspaces. Needs only be specified in special cases where workspace location cannot be derived from workspace type definition, e.g. sub-workspace

None

Returns: dict: Workspace Create Form data or None if the request fails.

Source code in pyxecm/otcs.py
def get_workspace_create_form(
    self,
    template_id: int,
    external_system_id: str = None,
    bo_type: str = None,
    bo_id: str = None,
    parent_id: int = None,
) -> dict | None:
    """Get the Workspace create form.

    Args:
        template_id (int): ID of the workspace template
        external_system_id (str, optional): Identifier of the external system (None if no external system)
        bo_type (str, optional): Business object type (None if no external system)
        bo_id (str, optional): Business object identifier / key (None if no external system)
        parent_id (int, optional): Parent ID of the workspaces. Needs only be specified in special
                                   cases where workspace location cannot be derived from workspace
                                   type definition, e.g. sub-workspace
    Returns:
        dict: Workspace Create Form data or None if the request fails.
    """

    request_url = self.config()[
        "businessworkspacecreateform"
    ] + "?template_id={}".format(template_id)
    # Is a parent ID specifified? Then we need to add it to the request URL
    if parent_id is not None:
        request_url += "&parent_id={}".format(parent_id)
    # Is this workspace connected to a business application / external system?
    if external_system_id and bo_type and bo_id:
        request_url += "&ext_system_id={}".format(external_system_id)
        request_url += "&bo_type={}".format(bo_type)
        request_url += "&bo_id={}".format(bo_id)
        logger.debug(
            "Include business object connection -> (%s, %s, %s) in workspace create form...",
            external_system_id,
            bo_type,
            bo_id,
        )
    request_header = self.request_form_header()

    logger.debug(
        "Get workspace create form for workspace template ID -> %s; calling -> %s",
        str(template_id),
        request_url,
    )

    if parent_id:
        failure_message = "Failed to get workspace create form for template -> {} and parent ID -> {}".format(
            template_id, parent_id
        )
    else:
        failure_message = "Failed to get workspace create form for template -> {} (no parent ID given)".format(
            template_id
        )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message=failure_message,
    )

get_workspace_instances(type_name='', type_id=None, expanded_view=True)

Get all workspace instances of a given type. This is a convenience wrapper method for get_workspace_by_type_and_name()

Parameters:

Name Type Description Default
type_name str

Name of the workspace type

''
type_id int

ID of the workspace_type

None
expanded_view bool

If 'False' then just search in recently accessed business workspace for this name and type. If 'True' (this is the default) then search in all workspaces for this name and type.

True

Returns: dict: Workspace information or None if the workspace is not found.

Source code in pyxecm/otcs.py
def get_workspace_instances(
    self, type_name: str = "", type_id: int = None, expanded_view: bool = True
):
    """Get all workspace instances of a given type. This is a convenience
       wrapper method for get_workspace_by_type_and_name()

    Args:
        type_name (str, optional): Name of the workspace type
        type_id (int, optional): ID of the workspace_type
        expanded_view (bool, optional): If 'False' then just search in recently
                                        accessed business workspace for this name and type.
                                        If 'True' (this is the default) then search in all
                                        workspaces for this name and type.
    Returns:
        dict: Workspace information or None if the workspace is not found.
    """

    # Omitting the name lets it return all instances of the type:
    return self.get_workspace_by_type_and_name(
        type_name=type_name, type_id=type_id, name="", expanded_view=expanded_view
    )

get_workspace_members(workspace_id, role_id)

Get the Workspace members of a given role.

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace template

required
role_id int

ID of the role

required

Returns: dict: Workspace member data or None if the request fails.

Source code in pyxecm/otcs.py
def get_workspace_members(self, workspace_id: int, role_id: int) -> dict | None:
    """Get the Workspace members of a given role.

    Args:
        workspace_id (int): ID of the workspace template
        role_id (int): ID of the role
    Returns:
        dict: Workspace member data or None if the request fails.
    """

    request_url = self.config()[
        "businessWorkspacesUrl"
    ] + "/{}/roles/{}/members".format(workspace_id, role_id)
    request_header = self.request_form_header()

    logger.debug(
        "Get workspace members for workspace ID -> %s and role ID -> %s; calling -> %s",
        str(workspace_id),
        str(role_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get workspace members",
    )

get_workspace_relationships(workspace_id, relationship_type=None, related_workspace_name=None, related_workspace_type_id=None)

Get the Workspace relationships to other workspaces. Optionally, filter criterias can be provided such as the related workspace name (starts with) or the related workspace TYPE ids (one or multiple)

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace template

required
relationship_type str

Either "parent" or "child" (or None = unspecified which is the default)

None
related_workspace_name str

filter for a certain workspace name in the related items.

None
related_workspace_type_id int | None

ID of related workspace type (or list of IDs)

None

Returns: dict: Workspace relationships or None if the request fails.

Source code in pyxecm/otcs.py
def get_workspace_relationships(
    self,
    workspace_id: int,
    relationship_type: str | None = None,
    related_workspace_name: str | None = None,
    related_workspace_type_id: int | None = None,
) -> dict | None:
    """Get the Workspace relationships to other workspaces. Optionally, filter criterias can be provided
       such as the related workspace name (starts with) or the related workspace TYPE ids (one or multiple)

    Args:
        workspace_id (int): ID of the workspace template
        relationship_type (str): Either "parent" or "child" (or None = unspecified which is the default)
        related_workspace_name (str, optional): filter for a certain workspace name in the related items.
        related_workspace_type_id (int | None): ID of related workspace type (or list of IDs)
    Returns:
        dict: Workspace relationships or None if the request fails.
    """

    request_url = (
        self.config()["businessWorkspacesUrl"]
        + "/"
        + str(workspace_id)
        + "/relateditems"
    )

    query = {}

    if relationship_type:
        query["where_relationtype"] = relationship_type

    if related_workspace_name:
        query["where_name"] = related_workspace_name

    if related_workspace_type_id:
        query["where_workspace_type_id"] = related_workspace_type_id

    encoded_query = urllib.parse.urlencode(query, doseq=False)
    request_url += "?{}".format(encoded_query)

    request_header = self.request_form_header()

    logger.debug(
        "Get related workspaces for workspace with ID -> %s; calling -> %s",
        str(workspace_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get related workspaces of workspace with ID -> {}".format(
            workspace_id
        ),
    )

get_workspace_roles(workspace_id)

Get the Workspace roles.

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace template or workspace

required

Returns: dict: Workspace Roles data or None if the request fails.

Source code in pyxecm/otcs.py
def get_workspace_roles(self, workspace_id: int) -> dict | None:
    """Get the Workspace roles.

    Args:
        workspace_id (int): ID of the workspace template or workspace
    Returns:
        dict: Workspace Roles data or None if the request fails.
    """

    request_url = (
        self.config()["businessWorkspacesUrl"] + "/" + str(workspace_id) + "/roles"
    )
    request_header = self.request_form_header()

    logger.debug(
        "Get workspace roles of workspace with ID -> %s; calling -> %s",
        str(workspace_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get roles of workspace with ID -> {}".format(
            workspace_id
        ),
    )

get_workspace_type_location(type_name='', type_id=None)

Determine the folder in which the workspace instances of a given type reside. Either the type ID or the type name need to be provided. NOTE: workspace types may not always have a default location for all its instances. In such case parent_id may just be the folder of the first delivered workspace instance.

Parameters:

Name Type Description Default
type_name str

Name of the workspace type. Defaults to "".

''
type_id int

ID of the workspace type. Defaults to None.

None

Returns:

Type Description
int | None

int | None: node ID of the parent folder

Source code in pyxecm/otcs.py
def get_workspace_type_location(
    self,
    type_name: str = "",
    type_id: int = None,
) -> int | None:
    """Determine the folder in which the workspace instances of a given type reside.
       Either the type ID or the type name need to be provided. NOTE: workspace types
       may not always have a default location for all its instances. In such case
       parent_id may just be the folder of the first delivered workspace instance.

    Args:
        type_name (str, optional): Name of the workspace type. Defaults to "".
        type_id (int, optional): ID of the workspace type. Defaults to None.

    Returns:
        int | None: node ID of the parent folder
    """

    # it seems there's no other way to get the workspace location configured for a
    # workspace type other then getting an example workspace of this type and see what
    # the parent is. The REST API used for get_workspace_types() does not deliver this information :-(
    response = self.get_workspace_by_type_and_name(
        type_name=type_name, type_id=type_id, page=1, limit=1
    )
    parent_id = self.get_result_value(response=response, key="parent_id")

    return parent_id

get_workspace_types(expand_workspace_info=True, expand_templates=True)

Get all workspace types configured in Extended ECM.

Parameters:

Name Type Description Default
expand_workspace_info bool

Controls if the workspace info is returned as well

True
expand_templates bool

Controls if the list of workspace templates per workspace typ is returned as well

True

Returns: dict: Workspace Types or None if the request fails.

Example response:
{
    'links': {
        'data': {...}
    },
    'results': [
        {
            'data': {
                'properties': {
                    'rm_enabled': False,
                    'templates': [
                        {
                            'id': 14471,
                            'name': 'Campaign',
                            'subtype': 848
                        },
                        ...
                    ],
                    'wksp_type_id': 35,
                    'wksp_type_name': 'Campaign'
                },
                'wksp_info': {
                    'wksp_type_icon': '/appimg/ot_bws/icons/13147%2Esvg?v=161108_84584'
                }
            }
        }
    ]
}
Source code in pyxecm/otcs.py
def get_workspace_types(
    self, expand_workspace_info: bool = True, expand_templates: bool = True
) -> dict | None:
    """Get all workspace types configured in Extended ECM.

    Args:
        expand_workspace_info (bool, optional): Controls if the workspace info
                                                is returned as well
        expand_templates (bool, optional): Controls if the list of workspace templates
                                           per workspace typ is returned as well
    Returns:
        dict: Workspace Types or None if the request fails.

        Example response:
        {
            'links': {
                'data': {...}
            },
            'results': [
                {
                    'data': {
                        'properties': {
                            'rm_enabled': False,
                            'templates': [
                                {
                                    'id': 14471,
                                    'name': 'Campaign',
                                    'subtype': 848
                                },
                                ...
                            ],
                            'wksp_type_id': 35,
                            'wksp_type_name': 'Campaign'
                        },
                        'wksp_info': {
                            'wksp_type_icon': '/appimg/ot_bws/icons/13147%2Esvg?v=161108_84584'
                        }
                    }
                }
            ]
        }
    """

    request_url = self.config()["businessWorkspaceTypesUrl"]
    if expand_templates:
        request_url += "?expand_templates=true"
    else:
        request_url += "?expand_templates=false"
    if expand_workspace_info:
        request_url += "&expand_wksp_info=true"
    else:
        request_url += "&expand_wksp_info=false"

    request_header = self.request_form_header()

    logger.debug("Get workspace types; calling -> %s", request_url)

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Failed to get workspace types",
    )

hostname()

Returns the hostname of Extended ECM (e.g. "otcs")

Returns:

Name Type Description
str str

hostname

Source code in pyxecm/otcs.py
def hostname(self) -> str:
    """Returns the hostname of Extended ECM (e.g. "otcs")

    Returns:
        str: hostname
    """
    return self.config()["hostname"]

import_physical_objects_codes(file_path, update_existing_codes=True)

Import Physical Objects codes from a config file that is uploaded from the Python pod

Parameters:

Name Type Description Default
file_path str

path + filename of config file in Python container filesystem

required
update_existing_codes bool

whether or not existing codes should be updated (default = True)

True

Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_physical_objects_codes(
    self, file_path: str, update_existing_codes: bool = True
) -> bool:
    """Import Physical Objects codes from a config file that is uploaded from the Python pod

    Args:
        file_path (str): path + filename of config file in Python container filesystem
        update_existing_codes (bool): whether or not existing codes should be updated (default = True)
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["physicalObjectsUrl"] + "/importCodes"

    # When we upload files using the 'files' parameter, the request must be encoded
    # as multipart/form-data, which allows binary data (like files) to be sent along
    # with other form data.
    # The requests library sets this header correctly if the 'files' parameter is provided.
    # So we just put the cookie in the header and trust the request library to add
    # the Content-Type = multipart/form-data :
    request_header = self.cookie()

    logger.debug(
        "Importing Physical Objects Codes from file -> '%s'; calling -> %s",
        file_path,
        request_url,
    )

    settings_post_data = {"updateExistingCodes": update_existing_codes}

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> '%s' does not exist in path -> '%s'!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=settings_post_data,
        files=settings_post_file,
        timeout=None,
        failure_message="Failed to import Physical Objects Codes from file -> '{}'".format(
            file_path
        ),
        parse_request_response=False,
    )

    if response and response.ok:
        return True

    return False

import_physical_objects_locators(file_path)

Import Physical Objects locators from a config file that is uploaded from the python pod

Parameters:

Name Type Description Default
file_path str

path + filename of config file in Python container filesystem

required

Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_physical_objects_locators(self, file_path: str) -> bool:
    """Import Physical Objects locators from a config file that is uploaded from the python pod

    Args:
        file_path (str): path + filename of config file in Python container filesystem
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["physicalObjectsUrl"] + "/importLocators"

    # When we upload files using the 'files' parameter, the request must be encoded
    # as multipart/form-data, which allows binary data (like files) to be sent along
    # with other form data.
    # The requests library sets this header correctly if the 'files' parameter is provided.
    # So we just put the cookie in the header and trust the request library to add
    # the Content-Type = multipart/form-data :
    request_header = self.cookie()

    logger.debug(
        "Importing Physical Objects Locators from file -> '%s'; calling -> %s",
        file_path,
        request_url,
    )

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> '%s' does not exist in path -> '%s'!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        files=settings_post_file,
        timeout=None,
        failure_message="Failed to import Physical Objects Locators from file -> '{}'".format(
            file_path
        ),
        parse_request_response=False,
    )

    if response and response.ok:
        return True

    return False

import_physical_objects_settings(file_path)

Import Physical Objects settings from a config file that is uploaded from the python pod

Parameters:

Name Type Description Default
file_path str

path + filename of config file in Python container filesystem

required

Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_physical_objects_settings(self, file_path: str) -> bool:
    """Import Physical Objects settings from a config file that is uploaded from the python pod

    Args:
        file_path (str): path + filename of config file in Python container filesystem
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["physicalObjectsUrl"] + "/importSettings"

    # When we upload files using the 'files' parameter, the request must be encoded
    # as multipart/form-data, which allows binary data (like files) to be sent along
    # with other form data.
    # The requests library sets this header correctly if the 'files' parameter is provided.
    # So we just put the cookie in the header and trust the request library to add
    # the Content-Type = multipart/form-data :
    request_header = self.cookie()

    logger.debug(
        "Importing Physical Objects Settings from server file -> '%s'; calling -> %s",
        file_path,
        request_url,
    )

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> '%s' does not exist in path -> '%s'!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        files=settings_post_file,
        timeout=None,
        failure_message="Failed to import Physical Objects settings from file -> '{}'".format(
            file_path
        ),
        parse_request_response=False,
    )

    if response and response.ok:
        return True

    return False

import_records_management_codes(file_path, update_existing_codes=True)

Import RM Codes from a file that is uploaded from the python pod

Parameters:

Name Type Description Default
file_path str

path + filename of settings file in Python container filesystem

required
update_existing_codes bool

Flag that controls whether existing table maintenance codes should be updated.

True

Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_records_management_codes(
    self, file_path: str, update_existing_codes: bool = True
) -> bool:
    """Import RM Codes from a file that is uploaded from the python pod

    Args:
        file_path (str): path + filename of settings file in Python container filesystem
        update_existing_codes (bool): Flag that controls whether existing table maintenance codes
                                      should be updated.
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["recordsManagementUrl"] + "/importCodes"

    # When we upload files using the 'files' parameter, the request must be encoded
    # as multipart/form-data, which allows binary data (like files) to be sent along
    # with other form data.
    # The requests library sets this header correctly if the 'files' parameter is provided.
    # So we just put the cookie in the header and trust the request library to add
    # the Content-Type = multipart/form-data :
    request_header = self.cookie()

    logger.debug(
        "Importing Records Management Codes from file -> '%s'; calling -> %s",
        file_path,
        request_url,
    )

    settings_post_data = {"updateExistingCodes": update_existing_codes}

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> '%s' does not exist in path -> '%s'!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=settings_post_data,
        files=settings_post_file,
        timeout=None,
        failure_message="Failed to import Records Management Codes from file -> '{}'".format(
            file_path
        ),
        parse_request_response=False,
    )

    if response and response.ok:
        return True

    return False

import_records_management_rsis(file_path, update_existing_rsis=True, delete_schedules=False)

Import RM RSIs from a config file that is uploaded from the Python pod

Parameters:

Name Type Description Default
file_path str

path + filename of config file in Python container filesystem

required
update_existing_rsis bool

whether or not existing RSIs should be updated (or ignored)

True
delete_schedules bool

whether RSI Schedules should be deleted

False

Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_records_management_rsis(
    self,
    file_path: str,
    update_existing_rsis: bool = True,
    delete_schedules: bool = False,
) -> bool:
    """Import RM RSIs from a config file that is uploaded from the Python pod

    Args:
        file_path (str): path + filename of config file in Python container filesystem
        update_existing_rsis (bool, optional): whether or not existing RSIs should be updated (or ignored)
        delete_schedules (bool, optional): whether RSI Schedules should be deleted
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["recordsManagementUrl"] + "/importRSIs"

    # When we upload files using the 'files' parameter, the request must be encoded
    # as multipart/form-data, which allows binary data (like files) to be sent along
    # with other form data.
    # The requests library sets this header correctly if the 'files' parameter is provided.
    # So we just put the cookie in the header and trust the request library to add
    # the Content-Type = multipart/form-data :
    request_header = self.cookie()

    logger.debug(
        "Importing Records Management RSIs from file -> '%s'; calling -> %s",
        file_path,
        request_url,
    )

    settings_post_data = {
        "updateExistingRSIs": update_existing_rsis,
        "deleteSchedules": delete_schedules,
    }

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> '%s' does not exist in path -> '%s'!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=settings_post_data,
        files=settings_post_file,
        timeout=None,
        failure_message="Failed to import Records Management RSIs from file -> '{}'".format(
            file_path
        ),
        parse_request_response=False,
    )

    if response and response.ok:
        return True

    return False

import_records_management_settings(file_path)

Import Records Management settings from a file that is uploaded from the python pod

Parameters:

Name Type Description Default
file_path str

path + filename of config file in Python container filesystem

required

Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_records_management_settings(self, file_path: str) -> bool:
    """Import Records Management settings from a file that is uploaded from the python pod

    Args:
        file_path (str): path + filename of config file in Python container filesystem
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["recordsManagementUrl"] + "/importSettings"

    # When we upload files using the 'files' parameter, the request must be encoded
    # as multipart/form-data, which allows binary data (like files) to be sent along
    # with other form data.
    # The requests library sets this header correctly if the 'files' parameter is provided.
    # So we just put the cookie in the header and trust the request library to add
    # the Content-Type = multipart/form-data :
    request_header = self.cookie()

    logger.debug(
        "Importing Records Management Settings from file -> '%s'; calling -> %s",
        file_path,
        request_url,
    )

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> '%s' does not exist in path -> '%s'!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        files=settings_post_file,
        timeout=None,
        failure_message="Failed to import Records Management Settings from file -> '{}'".format(
            file_path
        ),
        parse_request_response=False,
    )

    if response and response.ok:
        return True

    return False

import_security_clearance_codes(file_path, include_users=False)

Import Security Clearance codes from a config file that is uploaded from the python pod

Parameters:

Name Type Description Default
file_path str

path + filename of config file in Python container filesystem

required
include_users bool

defines if users should be included or not

False

Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_security_clearance_codes(
    self, file_path: str, include_users: bool = False
) -> bool:
    """Import Security Clearance codes from a config file that is uploaded from the python pod

    Args:
        file_path (str): path + filename of config file in Python container filesystem
        include_users (bool): defines if users should be included or not
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["securityClearancesUrl"] + "/importCodes"

    # When we upload files using the 'files' parameter, the request must be encoded
    # as multipart/form-data, which allows binary data (like files) to be sent along
    # with other form data.
    # The requests library sets this header correctly if the 'files' parameter is provided.
    # So we just put the cookie in the header and trust the request library to add
    # the Content-Type = multipart/form-data :
    request_header = self.cookie()

    logger.debug(
        "Importing Security Clearance Codes from file -> '%s'; calling -> %s",
        file_path,
        request_url,
    )

    settings_post_data = {"includeusers": include_users}

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> '%s' does not exist in path -> '%s'!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=settings_post_data,
        files=settings_post_file,
        timeout=None,
        failure_message="Failed to import Security Clearance Codes from file -> '{}'".format(
            file_path
        ),
        parse_request_response=False,
    )

    if response and response.ok:
        return True

    return False

initiate_draft_process(draftprocess_id, comment='')

Initiate a process (workflow instance) from a draft process.

Parameters:

Name Type Description Default
draftprocess_id int

ID of the draft process that has been created before with create_draft_process()

required
title str

Title of the process

required
comment str

comment of the process. Defaults to "".

''
due_date str

due date for the process. Defaults to "".

required
values dict | None

values for workflow attributes. Defaults to None.

required

Returns:

Name Type Description
dict | None

dict | None: Respinse of the REST API or None in case of an error.

Example dict | None
dict | None

{ 'links': { 'data': { 'self': { 'body': '', 'content_type': '', 'href': '/api/v2/draftprocesses/158037', 'method': 'PUT', 'name': '' } } }, 'results': { 'custom_message': 'Contract Approval Workflow was initiated successfully.', 'process_id': 165496, 'WorkID': None, 'WRID': None }

dict | None

}

Source code in pyxecm/otcs.py
def initiate_draft_process(
    self,
    draftprocess_id: int,
    comment: str = "",
) -> dict | None:
    """Initiate a process (workflow instance) from a draft process.

    Args:
        draftprocess_id (int): ID of the draft process that has been created before with create_draft_process()
        title (str): Title of the process
        comment (str, optional): comment of the process. Defaults to "".
        due_date (str, optional): due date for the process. Defaults to "".
        values (dict | None, optional): values for workflow attributes. Defaults to None.

    Returns:
        dict | None: Respinse of the REST API or None in case of an error.

        Example:
        {
            'links': {
                'data': {
                    'self': {
                        'body': '',
                        'content_type': '',
                        'href': '/api/v2/draftprocesses/158037',
                        'method': 'PUT',
                        'name': ''
                    }
                }
            },
            'results': {
                'custom_message': 'Contract Approval Workflow was initiated successfully.',
                'process_id': 165496,
                'WorkID': None,
                'WRID': None
            }
        }
    """

    request_url = self.config()["draftProcessUrl"] + "/" + str(draftprocess_id)
    request_header = self.request_form_header()

    logger.debug(
        "Initiate a process (workflow instance) from a draft process with ID -> %s; calling -> %s",
        str(draftprocess_id),
        request_url,
    )

    initiate_process_body_put_data = {
        "action": "Initiate",
        "comment": comment,
    }

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data={"body": json.dumps(initiate_process_body_put_data)},
        timeout=None,
        failure_message="Failed to initiate draft process with ID -> {}".format(
            draftprocess_id
        ),
    )

install_cs_application(application_name)

Install a CS Application (based on WebReports)

Parameters:

Name Type Description Default
application_name str

name of the application (e.g. OTPOReports, OTRMReports, OTRMSecReports)

required

Returns: dict: Response or None if the installation of the CS Application has failed.

Source code in pyxecm/otcs.py
def install_cs_application(self, application_name: str) -> dict | None:
    """Install a CS Application (based on WebReports)

    Args:
        application_name (str): name of the application (e.g. OTPOReports, OTRMReports, OTRMSecReports)
    Returns:
        dict: Response or None if the installation of the CS Application has failed.
    """

    install_cs_application_post_data = {"appName": application_name}

    request_url = self.config()["csApplicationsUrl"] + "/install"
    request_header = self.request_form_header()

    logger.debug(
        "Install CS Application -> '%s'; calling -> %s",
        application_name,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=install_cs_application_post_data,
        timeout=None,
        failure_message="Failed to install CS Application -> '{}'".format(
            application_name
        ),
    )

invalidate_authentication_ticket()

If a 401 HTTP error occurs we may want to invalidate the login ticket

Source code in pyxecm/otcs.py
def invalidate_authentication_ticket(self):
    """If a 401 HTTP error occurs we may want to invalidate the login ticket"""

    self._otcs_ticket = None
    self._cookie = None

is_configured()

Checks if the Content Server pod is configured to receive requests.

Returns: bool: True if pod is ready. False if pod is not yet ready.

Source code in pyxecm/otcs.py
def is_configured(self) -> bool:
    """Checks if the Content Server pod is configured to receive requests.

    Args:
        None.
    Returns:
        bool: True if pod is ready. False if pod is not yet ready.
    """

    request_url = self.config()["configuredUrl"]

    logger.debug("Trying to retrieve OTCS URL -> %s", request_url)

    try:
        response = requests.get(
            url=request_url,
            headers=REQUEST_JSON_HEADERS,
            timeout=REQUEST_TIMEOUT,
        )
    except requests.exceptions.RequestException as exception:
        logger.debug(
            "Unable to connect to -> %s; warning -> %s",
            request_url,
            str(exception),
        )
        return False

    if not response.ok:
        logger.debug(
            "Unable to connect to -> %s; status -> %s; warning -> %s",
            request_url,
            response.status_code,
            response.text,
        )
        return False

    return True

is_proxy(user_name)

Check if a user is defined as proxy of the current user. This method differentiates between the old (xGov) based implementation and the new Extended ECM platform one that was introduced with version 23.4.

Parameters:

Name Type Description Default
user_name str

user to test (login name)

required

Returns: bool: True is user is proxy of current user. False if not.

Source code in pyxecm/otcs.py
def is_proxy(self, user_name: str) -> bool:
    """Check if a user is defined as proxy of the current user.
       This method differentiates between the old (xGov) based
       implementation and the new Extended ECM platform one
       that was introduced with version 23.4.

    Args:
        user_name (str): user to test (login name)
    Returns:
        bool: True is user is proxy of current user. False if not.
    """

    version_number = self.get_server_version()
    # Split the version number by dot
    parts = version_number.split(".")
    # Take the first two parts and join them back with a dot
    stripped_version = ".".join(parts[:2])

    try:
        version_number = float(stripped_version)
    except ValueError:
        version_number = 99.99  # Set to version 99.99 for "main"

    if version_number >= 23.4:
        response = self.get_user_proxies(use_v2=True)
        if self.exist_result_item(
            response=response, key="name", value=user_name, property_name=""
        ):
            return True
        else:
            return False
    else:
        response = self.get_user_proxies(use_v2=False)
        if not response or not "proxies" in response:
            return False
        proxies = response["proxies"]

        for proxy in proxies:
            if proxy["name"] == user_name:
                return True
        return False

is_ready()

Checks if the Content Server pod is ready to receive requests.

Returns: bool: True if pod is ready. False if pod is not yet ready.

Source code in pyxecm/otcs.py
def is_ready(self) -> bool:
    """Checks if the Content Server pod is ready to receive requests.

    Args:
        None.
    Returns:
        bool: True if pod is ready. False if pod is not yet ready.
    """

    request_url = self.config()["isReady"]

    logger.debug("Trying to retrieve OTCS URL -> %s", request_url)

    try:
        response = requests.get(
            url=request_url,
            headers=REQUEST_JSON_HEADERS,
            timeout=2,
        )
    except requests.exceptions.RequestException as exception:
        logger.debug(
            "Unable to connect to -> %s; warning -> %s",
            request_url,
            str(exception),
        )
        return False

    if not response.status_code == 200:
        logger.debug(
            "Unable to connect to -> %s; status -> %s; warning -> %s",
            request_url,
            response.status_code,
            response.text,
        )
        return False

    return True

load_items(node_id, folder_path=None, current_depth=0, workspace_type=None, workspace_id=None, workspace_name=None, workspace_description=None, filter_workspace_depth=None, filter_workspace_subtypes=None, filter_workspace_category=None, filter_workspace_attributes=None, filter_item_depth=None, filter_item_category=None, filter_item_attributes=None, workspace_metadata=True, item_metadata=True, skip_existing_downloads=True)

Create a Pandas Data Frame by traversing a given Content Server hierarchy and collecting workspace and document items.

Parameters:

Name Type Description Default
node_id int

currrent Node ID (in recursive processing). Initially this is the starting node (root of the traversal)

required
folder_path str

The current path from the starting node to the current node. Defaults to None.

None
current_depth int

The current depth in the tree that is traversed.

0
workspace_type int | None

Type of the workspace (if already found in the hierarchy). Defaults to None.

None
workspace_id int | None

ID of the workspace (if already found in the hierarchy). Defaults to None.

None
workspace_name str | None

Name of the workspace (if already found in the hierarchy). Defaults to None.

None
workspace_description str | None

Description of the workspace (if already found in the hierarchy). Defaults to None.

None
filter_workspace_depth int | None

Additive filter criterium for workspace path depth. Defaults to None = filter not active.

None
filter_workspace_subtype list | None

Additive filter criterium for workspace type. Defaults to None = filter not active.

required
filter_workspace_category str | None

Additive filter criterium for workspace category. Defaults to None = filter not active.

None
filter_workspace_attributes dict | list

Additive filter criterium for workspace attribute values. Defaults to None = filter not active

None
filter_item_depth int | None

Additive filter criterium for item path depth. Defaults to None = filter not active.

None
filter_item_category str | None

Additive filter criterium for item category. Defaults to None = filter not active.

None
filter_item_attributes dict | list

Additive filter criterium for item attribute values. Defaults to None = filter not active

None

Returns: bool: True = success, False = Error

Source code in pyxecm/otcs.py
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
def load_items(
    self,
    node_id: int,
    folder_path: list | None = None,
    current_depth: int = 0,
    workspace_type: int | None = None,
    workspace_id: int | None = None,
    workspace_name: str | None = None,
    workspace_description: str | None = None,
    filter_workspace_depth: int | None = None,
    filter_workspace_subtypes: list | None = None,
    filter_workspace_category: str | None = None,
    filter_workspace_attributes: dict | list | None = None,
    filter_item_depth: int | None = None,
    filter_item_category: str | None = None,
    filter_item_attributes: dict | list | None = None,
    workspace_metadata: bool = True,
    item_metadata: bool = True,
    skip_existing_downloads: bool = True,
) -> bool:
    """Create a Pandas Data Frame by traversing a given Content Server hierarchy and collecting workspace and document items.

    Args:
        node_id (int): currrent Node ID (in recursive processing). Initially this is the starting node (root of the traversal)
        folder_path (str, optional): The current path from the starting node to the current node. Defaults to None.
        current_depth (int): The current depth in the tree that is traversed.
        workspace_type (int | None, optional): Type of the workspace (if already found in the hierarchy). Defaults to None.
        workspace_id (int | None, optional): ID of the workspace (if already found in the hierarchy). Defaults to None.
        workspace_name (str | None, optional): Name of the workspace (if already found in the hierarchy). Defaults to None.
        workspace_description (str | None, optional): Description of the workspace (if already found in the hierarchy). Defaults to None.
        filter_workspace_depth (int | None, optional): Additive filter criterium for workspace path depth. Defaults to None = filter not active.
        filter_workspace_subtype (list | None, optional): Additive filter criterium for workspace type. Defaults to None = filter not active.
        filter_workspace_category (str | None, optional): Additive filter criterium for workspace category. Defaults to None = filter not active.
        filter_workspace_attributes (dict | list, optional): Additive filter criterium for workspace attribute values. Defaults to None = filter not active
        filter_item_depth (int | None, optional): Additive filter criterium for item path depth. Defaults to None = filter not active.
        filter_item_category (str | None, optional): Additive filter criterium for item category. Defaults to None = filter not active.
        filter_item_attributes (dict | list, optional): Additive filter criterium for item attribute values. Defaults to None = filter not active
    Returns:
        bool: True = success, False = Error
    """

    if folder_path is None:
        folder_path = []  # required for list concatenation below

    # Create folder if it does not exist
    try:
        os.makedirs(self._download_dir)
    except FileExistsError:
        pass

    # Aquire and Release threading semaphore to limit parallel executions
    # to not overload the source Content Server system:
    with self._semaphore:
        subnodes = self.get_subnodes(parent_node_id=node_id)

    if subnodes is None:
        subnodes = {"results": []}

    # Initialize traversal threads:
    traversal_threads = []

    for subnode in subnodes.get("results", []):
        subnode = subnode.get("data").get("properties")

        # Initiaze download threads for this subnode:
        download_threads = []

        match subnode["type"]:

            case 0 | 848:  # folder or workspace
                # First we check if we have found a workspace already:
                if not workspace_id:
                    # Second we apply the defined filters to the current node. Only "workspaces"
                    # that comply with ALL provided filters are considered and written into the data frame
                    found_workspace = self.apply_filter(
                        node=subnode,
                        current_depth=current_depth,
                        filter_depth=filter_workspace_depth,
                        filter_subtypes=filter_workspace_subtypes,
                        filter_category=filter_workspace_category,
                        filter_attributes=filter_workspace_attributes,
                    )
                else:
                    logger.info(
                        "Found folder or workspace -> '%s' (%s) inside workspace with ID -> %s. So this container cannot be a workspace.",
                        subnode["name"],
                        subnode["id"],
                        workspace_id,
                    )
                    # otherwise the current node cannot be a workspace as we are already in a workspace!
                    # For future improvements we could look at supporting sub-workspaces:
                    found_workspace = False

                if found_workspace:
                    logger.info(
                        "Found workspace -> '%s' (%s) in depth -> %s. Adding to Data Frame...",
                        subnode["name"],
                        subnode["id"],
                        current_depth,
                    )
                    # DON'T change workspace_id here!
                    # This would break the for loop logic!

                    #
                    # Construct a dictionary 'row' that we will add
                    # to the resulting data frame:
                    #
                    row = {}
                    row["workspace_type"] = subnode["type"]
                    row["workspace_id"] = subnode["id"]
                    row["workspace_name"] = subnode["name"]
                    row["workspace_description"] = subnode["description"]
                    row["workspace_outer_path"] = folder_path
                    if workspace_metadata:
                        categories = self.get_node_categories(
                            subnode["id"], metadata=False
                        )
                        if categories and categories["results"]:
                            for category in categories["results"]:
                                if (
                                    not "data" in category
                                    or not "categories" in category["data"]
                                ):
                                    continue
                                attributes = category["data"]["categories"]
                                for key in attributes:
                                    value = attributes[key]
                                    row["workspace_" + key] = value

                    # Now we add the article to the Pandas Data Frame in the Data class:
                    with self._data.lock():
                        self._data.append(row)
                    subfolder = []  # now we switch to workspace inner path
                # end if found_workspace:
                else:  # we treat the current folder / workspace just as a container
                    logger.info(
                        "Node -> '%s' (%s) in depth -> %s is NOT a workspace. Keep traversing...",
                        subnode["name"],
                        subnode["id"],
                        current_depth,
                    )
                    subfolder = folder_path + [subnode["name"]]

                # Recursive call to start threads for sub-items:
                thread = threading.Thread(
                    target=self.load_items,
                    args=(
                        subnode["id"],
                        subfolder,
                        current_depth + 1,
                        (
                            workspace_type  # pass down initial parameter value if subnode is not the workspace
                            if not found_workspace
                            else subnode["type"]
                        ),
                        (
                            workspace_id  # pass down initial parameter value if subnode is not the workspace
                            if not found_workspace
                            else subnode["id"]
                        ),
                        (
                            workspace_name  # pass down initial parameter value if subnode is not the workspace
                            if not found_workspace
                            else subnode["name"]
                        ),
                        (
                            workspace_description  # pass down initial parameter value if subnode is not the workspace
                            if not found_workspace
                            else subnode["description"]
                        ),
                        filter_workspace_depth,
                        filter_workspace_subtypes,
                        filter_workspace_category,
                        filter_workspace_attributes,
                        filter_item_depth,
                        filter_item_category,
                        filter_item_attributes,
                        workspace_metadata,
                        item_metadata,
                        skip_existing_downloads,
                    ),
                    name="traverse_node_{}".format(subnode["id"]),
                )
                thread.start()
                traversal_threads.append(thread)

            case 1:  # shortcuts
                pass

            case 854:  # Related Workspaces - we don't want to run into loops!
                pass

            case 751:  # E-Mail folders
                pass

            case 123469:  # Forum
                pass

            case 144:  # document
                # We apply the defined filters to the current node. Only "documents"
                # that comply with ALL provided filters are considered and written into the data frame
                found_document = self.apply_filter(
                    node=subnode,
                    current_depth=current_depth,
                    filter_depth=filter_item_depth,
                    filter_category=filter_item_category,
                    filter_attributes=filter_item_attributes,
                )

                if not found_document:
                    continue

                # We use the node ID as the filename to avoid any
                # issues with too long or not valid file names.
                # As the Pandas DataFrame has all information
                # this is easy to resolve at upload time.
                file_path = "{}/{}".format(self._download_dir, subnode["id"])

                # We only consider documents that are inside the defined "workspaces":
                if workspace_id:
                    logger.info(
                        "Found document -> '%s' (%s) in depth -> %s inside workspace -> '%s' (%s)",
                        subnode["name"],
                        subnode["id"],
                        current_depth,
                        workspace_name,
                        workspace_id,
                    )
                else:
                    logger.warning(
                        "Found document -> '%s' (%s) in depth -> %s outside of workspace",
                        subnode["name"],
                        subnode["id"],
                        current_depth,
                    )

                # We download only if not downloaded before or if downloaded
                # before but forced to re-download:
                if not os.path.exists(file_path) or not skip_existing_downloads:
                    #
                    # Start anasynchronous Download Thread:
                    #
                    logger.info(
                        "Downloading file -> %s...",
                        file_path,
                    )
                    thread = threading.Thread(
                        target=self.download_document_multi_threading,
                        args=(subnode["id"], file_path),
                        name="download_document_node_{}".format(subnode["id"]),
                    )
                    thread.start()
                    download_threads.append(thread)
                else:
                    logger.info(
                        "File -> %s has been downloaded before. Skipping download...",
                        file_path,
                    )

                #
                # Construct a dictionary 'row' that we will add
                # to the resulting data frame:
                #
                row = {}
                # First we include some key workspace data to associate
                # the itemwith the workspace:
                row["workspace_type"] = workspace_type
                row["workspace_id"] = workspace_id
                row["workspace_name"] = workspace_name
                row["workspace_description"] = workspace_description
                row["item_id"] = str(subnode["id"])
                row["item_name"] = subnode["name"]
                row["item_description"] = subnode["description"]
                row["item_path"] = folder_path
                row["item_download_name"] = str(subnode["id"])
                row["item_mime_type"] = subnode["mime_type"]
                if item_metadata:
                    categories = self.get_node_categories(
                        subnode["id"], metadata=False
                    )
                    if categories and categories["results"]:
                        for category in categories["results"]:
                            if (
                                not "data" in category
                                or not "categories" in category["data"]
                            ):
                                continue
                            attributes = category["data"]["categories"]
                            for key in attributes:
                                value = attributes[key]
                                row["item_" + key] = value

                # Now we add the row to the Pandas Data Frame in the Data class:
                logger.info(
                    "Adding document -> '%s' (%s) to data frame...",
                    row["item_name"],
                    row["item_id"],
                )
                with self._data.lock():
                    self._data.append(row)
            case 140:  # url
                logger.info(
                    "Found URL object %s with %s", subnode["id"], subnode["url"]
                )

            case _:
                logger.warning(
                    "Don't know what to do with item -> %s (%s) of type %s",
                    subnode["name"],
                    subnode["id"],
                    subnode["type"],
                )

        # Wait for all download threads to complete:
        for thread in download_threads:
            thread.join()

    # Wait for all traversal threads to complete:
    for thread in traversal_threads:
        thread.join()

    return True

lookup_node(parent_node_id, category, attribute, value)

Lookup the node under a parent node that has a specified value in a category attribute.

Parameters:

Name Type Description Default
parent_node_id int

Node ID of the parent (typically folder or workspace)

required
category str

name of the category

required
attribute str

name of the attribute that includes the value to match with

required
value str

given lookup value

required

Returns:

Name Type Description
dict dict

Node or None if the REST API fails.

Source code in pyxecm/otcs.py
def lookup_node(
    self, parent_node_id: int, category: str, attribute: str, value: str
) -> dict:
    """Lookup the node under a parent node that has a specified value in a category attribute.

    Args:
        parent_node_id (int): Node ID of the parent (typically folder or workspace)
        category (str): name of the category
        attribute (str): name of the attribute that includes the value to match with
        value (str): given lookup value

    Returns:
        dict: Node or None if the REST API fails.
    """

    response = self.get_subnodes(
        parent_node_id=parent_node_id,
        limit=250,
        fields=["properties", "categories"],
        metadata=True,
    )
    if not response or not response.get("results", None):
        return None

    nodes = response["results"]
    for node in nodes:
        schema = node["metadata"]["categories"]
        data = node["data"]["categories"]
        for cat_data, cat_schema in zip(data, schema):

            data_values = list(cat_data.values())
            schema_values = list(cat_schema.values())
            # Schema has one additional element (the first one) representing
            # the category object itself. This includes the name. We need
            # to remove (pop) it from the schema list to make sure the schema list
            # and the data list have the same number of items. Otherwise
            # the following for loop with zip() would not properly align the
            # two lists:
            category_name = schema_values.pop(0)["name"]
            if category_name == category:
                for attr_data, attr_schema in zip(data_values, schema_values):
                    attr_name = attr_schema["name"]
                    if attr_name == attribute:
                        if isinstance(attr_data, list):
                            if value in attr_data:
                                return node
                        else:
                            if value == attr_data:
                                return node
                # we can break here and continue with the next node
                # as we had the right category but did not find the matching value
                break

    logger.warning(
        "Coudn't find a node with the value -> '%s' in the attribute -> '%s' of category -> '%s'.",
        value,
        attribute,
        category,
    )

    return None

lookup_result_value(response, key, value, return_key)

Lookup a property value based on a provided key / value pair in the response properties of an Extended ECM REST API call.

Parameters:

Name Type Description Default
response dict

REST response from an OTCS REST Call

required
key str

property name (key)

required
value str

value to find in the item with the matching key

required
return_key str

determines which value to return based on the name of the dict key

required

Returns: str: value of the property with the key defined in "return_key" or None if the lookup fails

Source code in pyxecm/otcs.py
def lookup_result_value(
    self, response: dict, key: str, value: str, return_key: str
) -> str | None:
    """Lookup a property value based on a provided key / value pair in the
       response properties of an Extended ECM REST API call.

    Args:
        response (dict): REST response from an OTCS REST Call
        key (str): property name (key)
        value (str): value to find in the item with the matching key
        return_key (str): determines which value to return based on the name of the dict key
    Returns:
        str: value of the property with the key defined in "return_key"
             or None if the lookup fails
    """

    if not response:
        return None
    if not "results" in response:
        return None

    results = response["results"]
    # check if results is a list or a dict (both is possible -
    # dependent on the actual REST API):
    if isinstance(results, dict):
        # result is a dict - we don't need index value:
        data = results["data"]
        if isinstance(data, dict):
            # data is a dict - we don't need index value:
            properties = data["properties"]
            if (
                key in properties
                and properties[key] == value
                and return_key in properties
            ):
                return properties[return_key]
            else:
                return None
        elif isinstance(data, list):
            # data is a list - this has typically just one item, so we use 0 as index
            for item in data:
                properties = item["properties"]
                if (
                    key in properties
                    and properties[key] == value
                    and return_key in properties
                ):
                    return properties[return_key]
            return None
        else:
            logger.error(
                "Data needs to be a list or dict but it is -> %s", str(type(data))
            )
            return None
    elif isinstance(results, list):
        # result is a list - we need index value
        for result in results:
            data = result["data"]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                properties = data["properties"]
                if (
                    key in properties
                    and properties[key] == value
                    and return_key in properties
                ):
                    return properties[return_key]
            elif isinstance(data, list):
                # data is a list we iterate through the list and try to find the key:
                for item in data:
                    properties = item["properties"]
                    if (
                        key in properties
                        and properties[key] == value
                        and return_key in properties
                    ):
                        return properties[return_key]
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s",
                    str(type(data)),
                )
                return None
        return None
    else:
        logger.error(
            "Result needs to be a list or dict but it is -> %s", str(type(results))
        )
        return None

otcs_ticket()

Return the OTCS ticket

Returns:

Name Type Description
str str | None

String with the OTCS ticket

Source code in pyxecm/otcs.py
def otcs_ticket(self) -> str | None:
    """Return the OTCS ticket

    Returns:
        str: String with the OTCS ticket
    """

    return self._otcs_ticket

parse_request_response(response_object, additional_error_message='', show_error=True)

Converts the text property of a request response object to a Python dict in a safe way that also handles exceptions.

Content Server may produce corrupt response when it gets restarted
or hitting resource limits. So we try to avoid a fatal error and bail
out more gracefully.

Parameters:

Name Type Description Default
response_object object

this is reponse object delivered by the request call

required
additional_error_message str

print a custom error message

''
show_error bool

if True log an error, if False log a warning

True

Returns:

Name Type Description
dict dict | None

response or None in case of an error

Source code in pyxecm/otcs.py
def parse_request_response(
    self,
    response_object: object,
    additional_error_message: str = "",
    show_error: bool = True,
) -> dict | None:
    """Converts the text property of a request response object to a Python dict in a safe way
        that also handles exceptions.

        Content Server may produce corrupt response when it gets restarted
        or hitting resource limits. So we try to avoid a fatal error and bail
        out more gracefully.

    Args:
        response_object (object): this is reponse object delivered by the request call
        additional_error_message (str): print a custom error message
        show_error (bool): if True log an error, if False log a warning

    Returns:
        dict: response or None in case of an error
    """

    if not response_object:
        return None

    if not response_object.text:
        logger.warning("Response text is empty. Cannot decode response.")
        return None

    try:
        dict_object = json.loads(response_object.text)
    except json.JSONDecodeError as exception:
        if additional_error_message:
            message = "Cannot decode response as JSon. {}; error -> {}".format(
                additional_error_message, exception
            )
        else:
            message = "Cannot decode response as JSon; error -> {}".format(
                exception
            )
        if show_error:
            logger.error(message)
        else:
            logger.debug(message)
        return None
    else:
        return dict_object

purge_node(node_id)

Purge an item in the recycle bin (final destruction)

Parameters:

Name Type Description Default
node_id int | list

ID(s) of the node(s) to be finally deleted

required
Source code in pyxecm/otcs.py
def purge_node(self, node_id: int | list):
    """Purge an item in the recycle bin (final destruction)

    Args:
        node_id (int | list): ID(s) of the node(s) to be finally deleted
    """

    request_url = self.config()["recycleBinUrl"] + "/nodes/purge"
    request_header = self.request_form_header()

    if isinstance(node_id, list):
        purge_data = {"ids": node_id}
    else:
        purge_data = {"ids": [node_id]}

    logger.debug(
        "Purge node(s) with ID(s) -> %s from recycle bin; calling -> %s",
        str(node_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=purge_data,
        timeout=None,
        failure_message="Failed to purge node with ID -> {} from the recycle bin".format(
            node_id
        ),
    )

reauthenticate(request_cookie, thread_safe=True)

Re-Authenticate after session timeout. This implementation supports thread-safe reauthentication, making sure not multiple threads reauthenticate at the same time.

Parameters:

Name Type Description Default
request_cookie dict

the cookie used in the REST API call that produced the 401 HTTP error triggering the re-authentication. We use it to compare it with the current cookie to see if another thread may have done the reauthentication and updated the cookie already.

required
thread_safe bool

If True a thread-safe implementation is done. Defaults to True.

True

Returns:

Type Description
dict | None

dict | None: cookie information returned by authenticate()

Source code in pyxecm/otcs.py
def reauthenticate(
    self, request_cookie: dict, thread_safe: bool = True
) -> dict | None:
    """Re-Authenticate after session timeout. This implementation
       supports thread-safe reauthentication, making sure not multiple
       threads reauthenticate at the same time.

    Args:
        request_cookie: the cookie used in the REST API call that
                        produced the 401 HTTP error triggering the re-authentication.
                        We use it to compare it with the current cookie to see
                        if another thread may have done the reauthentication and
                        updated the cookie already.
        thread_safe (bool, optional): If True a thread-safe implementation is done.
                                      Defaults to True.

    Returns:
        dict | None: cookie information returned by authenticate()
    """

    if not thread_safe:
        return self.authenticate(revalidate=True)

    # Lock access to session for thread-safe reads
    with self._session_lock:
        # Check if the cookie used for the REST call is still the current cookie:
        if request_cookie != self.cookie():
            # Another thread has already re-authenticated; skip re-authentication
            logger.debug(
                "Session has already been renewed with new cookie. Skip re-authentication and return new cookie -> %s",
                str(self.cookie()),
            )
            # return the new cookie:
            return self.cookie()

    # If the session is invalid, try to acquire the semaphore and renew it
    if self._authentication_semaphore.acquire(blocking=False):
        # Renew the session (only one thread gets here)
        logger.debug(
            "Session has expired - need to renew old request cookie -> %s",
            str(request_cookie),
        )

        try:
            # The 'with' automatically acquires and releases the lock on 'authentication_condition'
            with self._authentication_condition:
                logger.debug("Current thread got the authentication condition...")
                # We use the _session_lock to prevent race conditions
                # while reading / writing the self._cookie (which is modified
                # by the authenticate() method):
                with self._session_lock:
                    logger.debug(
                        "Current thread got the session lock and tries to re-authenticate to get new cookie"
                    )
                    try:
                        self.authenticate(revalidate=True)
                        logger.debug(
                            "Session renewal successful, new cookie -> %s",
                            str(self.cookie()),
                        )
                        time.sleep(4)
                    except Exception as auth_error:
                        logger.error(
                            "Reauthentication failed with error -> %s",
                            str(auth_error),
                        )
                        raise
                logger.debug("Lift session lock and notify waiting threads...")
                # Notify all waiting threads that session is renewed:
                self._authentication_condition.notify_all()
                logger.warning("All waiting threads have been notified.")
        finally:
            # Ensure the semaphore is released even if an error occurs
            self._authentication_semaphore.release()
            logger.debug("Semaphore released after session renewal.")
        logger.debug("Session renewing thread continues with retry of request...")
    else:
        # Other threads wait for session renewal to complete
        logger.debug(
            "Session has expired but another thread is working on renewal - current thread waiting for re-authentication..."
        )

        with self._authentication_condition:
            logger.debug("Waiting thread got the authentication condition...")
            # IMPORTANT: Don't do a session lock here. This can produce a deadlock.
            # Reason: self._authentication_condition.wait() does not release the self._session_lock
            # but just the self._authentication_condition lock.

            # Check if session is not yet renewed (still has the old cookie used for the request)
            while request_cookie == self.cookie():
                # This code is very unlikely to be executed as
                # _authentication_condition and _session_lock protect
                # the else clause from running in parallel to the if clause.
                logger.debug("Thread is now waiting for session renewal...")
                # Wait for notification that the session is renewed:
                self._authentication_condition.wait()
                logger.debug(
                    "Thread received notification, session renewal complete."
                )
            logger.debug(
                "Waiting thread got the new cookie -> %s.", str(self.cookie())
            )
        logger.debug(
            "Waiting thread released the authentication condition and continues with retry of request..."
        )

    return self.cookie()

register_workspace_template(node_id)

Register a workspace template as project template for Extended ECM for Engineering

Parameters:

Name Type Description Default
node_id int

node ID of the Extended ECM workspace template

required

Returns: dict: Response of request or None if the registration of the workspace template has failed.

Source code in pyxecm/otcs.py
def register_workspace_template(self, node_id: int) -> dict | None:
    """Register a workspace template as project template for Extended ECM for Engineering

    Args:
        node_id (int): node ID of the Extended ECM workspace template
    Returns:
        dict: Response of request or None if the registration of the workspace template has failed.
    """

    registration_post_data = {"ids": "{{ {} }}".format(node_id)}

    request_url = self.config()["xEngProjectTemplateUrl"]

    request_header = self.request_form_header()

    logger.debug(
        "Register workspace template with ID -> %s for Extended ECM for Engineering; calling -> %s",
        str(node_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=registration_post_data,
        timeout=None,
        failure_message="Failed to register Workspace Template with ID -> {} for Extended ECM for Engineering".format(
            node_id
        ),
    )

remove_workspace_member(workspace_id, role_id, member_id, show_warning=True)

Remove a member from a workspace role. Check that the user is currently a member.

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace

required
role_id int

ID of the role

required
member_id int

User or Group Id

required
show_warning bool

If True logs a warning if member is not in role

True

Returns: dict: Workspace Role Membership or None if the request fails.

Source code in pyxecm/otcs.py
def remove_workspace_member(
    self, workspace_id: int, role_id: int, member_id: int, show_warning: bool = True
) -> dict | None:
    """Remove a member from a workspace role. Check that the user is currently a member.

    Args:
        workspace_id (int): ID of the workspace
        role_id (int): ID of the role
        member_id (int): User or Group Id
        show_warning (bool, optional): If True logs a warning if member is not in role
    Returns:
        dict: Workspace Role Membership or None if the request fails.
    """

    logger.debug(
        "Check if user/group with ID -> %s is in role with ID -> %s of workspace with ID -> %s",
        str(member_id),
        str(role_id),
        str(workspace_id),
    )

    workspace_members = self.get_workspace_members(
        workspace_id=workspace_id, role_id=role_id
    )

    if not self.exist_result_item(workspace_members, "id", member_id):
        if show_warning:
            logger.warning(
                "User/group with ID -> %s is not a member of role with ID -> %s of workspace with ID -> %s",
                str(member_id),
                str(role_id),
                str(workspace_id),
            )
        return None

    request_url = self.config()[
        "businessWorkspacesUrl"
    ] + "/{}/roles/{}/members/{}".format(workspace_id, role_id, member_id)
    request_header = self.request_form_header()

    logger.debug(
        "Removing user/group with ID -> %s from role with ID -> %s of workspace with ID -> %s; calling -> %s",
        str(member_id),
        str(role_id),
        str(workspace_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="DELETE",
        headers=request_header,
        timeout=None,
        failure_message="Failed to remove user/group with ID -> {} from role with ID -> {} of workspace with ID -> {}".format(
            member_id, role_id, workspace_id
        ),
    )

remove_workspace_members(workspace_id, role_id, show_warning=True)

Remove all members from a workspace role. Check that the user is currently a member.

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace

required
role_id int

ID of the role

required
show_warning bool

If True logs a warning if member is not in role

True

Returns: dict: Workspace Role Membership or None if the request fails.

Source code in pyxecm/otcs.py
def remove_workspace_members(
    self, workspace_id: int, role_id: int, show_warning: bool = True
) -> bool:
    """Remove all members from a workspace role. Check that the user is currently a member.

    Args:
        workspace_id (int): ID of the workspace
        role_id (int): ID of the role
        show_warning (bool, optional): If True logs a warning if member is not in role
    Returns:
        dict: Workspace Role Membership or None if the request fails.
    """

    workspace_members = self.get_workspace_members(
        workspace_id=workspace_id, role_id=role_id
    )

    # Get the list of existing workspace_member ids:
    workspace_member_ids = self.get_result_values(workspace_members, "id")
    if not workspace_member_ids:
        return False

    for workspace_member_id in workspace_member_ids:
        self.remove_workspace_member(
            workspace_id=workspace_id,
            role_id=role_id,
            member_id=workspace_member_id,
            show_warning=show_warning,
        )

    return True

rename_node(node_id, name, description, name_multilingual=None, description_multilingual=None)

Change the name and description of a node.

Parameters:

Name Type Description Default
node_id int

ID of the node. You can use the get_volume() function below to to the node id for a volume.

required
name str

New name of the node.

required
description str

New description of the node.

required
name_multilingual dict

multi-lingual node names

None
description_multilingual dict

multi-lingual description

None

Returns: dict: Request response or None if the renaming fails.

Source code in pyxecm/otcs.py
def rename_node(
    self,
    node_id: int,
    name: str,
    description: str,
    name_multilingual: dict | None = None,
    description_multilingual: dict | None = None,
) -> dict | None:
    """Change the name and description of a node.

    Args:
        node_id (int): ID of the node. You can use the get_volume() function below to
                           to the node id for a volume.
        name (str): New name of the node.
        description (str): New description of the node.
        name_multilingual (dict, optional): multi-lingual node names
        description_multilingual (dict, optional): multi-lingual description
    Returns:
        dict: Request response or None if the renaming fails.
    """

    rename_node_put_body = {"name": name, "description": description}

    if name_multilingual:
        rename_node_put_body["name_multilingual"] = name_multilingual
    if description_multilingual:
        rename_node_put_body["description_multilingual"] = description_multilingual

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id)
    request_header = self.request_form_header()

    logger.debug(
        "Rename node with ID -> %s to -> '%s'; calling -> %s",
        str(node_id),
        name,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data={"body": json.dumps(rename_node_put_body)},
        timeout=None,
        failure_message="Failed to rename node with ID -> {} to -> '{}'".format(
            node_id, name
        ),
    )

replace_transport_placeholders(zip_file_path, replacements)

Search and replace strings in the XML files of the transport package

Parameters:

Name Type Description Default
zip_file_path str

Path to transport zip file

required
replacements list of dicts

List of replacement values; dict needs to have two values: * placeholder: text to replace * value: text to replace with

required

Returns: Filename to the updated zip file

Source code in pyxecm/otcs.py
def replace_transport_placeholders(
    self, zip_file_path: str, replacements: list
) -> bool:
    """Search and replace strings in the XML files of the transport package

    Args:
        zip_file_path (str): Path to transport zip file
        replacements (list of dicts): List of replacement values; dict needs to have two values:
                                     * placeholder: text to replace
                                     * value: text to replace with
    Returns:
        Filename to the updated zip file
    """

    if not os.path.isfile(zip_file_path):
        logger.error("Zip file -> '%s' not found.", zip_file_path)
        return False

    # Extract the zip file to a temporary directory
    zip_file_folder = os.path.splitext(zip_file_path)[0]
    with zipfile.ZipFile(zip_file_path, "r") as zfile:
        zfile.extractall(zip_file_folder)

    modified = False

    # Replace search pattern with replace string in all XML files in the directory and its subdirectories
    for replacement in replacements:
        if not "value" in replacement:
            logger.error(
                "Replacement needs a value but it is not specified. Skipping..."
            )
            continue
        if "enabled" in replacement and not replacement["enabled"]:
            logger.debug(
                "Replacement for transport -> '%s' is disabled. Skipping...",
                zip_file_path,
            )
            continue
        # there are two types of replacements:
        # 1. XPath - more elegant and powerful
        # 2. Search & Replace - basically treat the XML file like a text file and do a search & replace
        if "xpath" in replacement:
            logger.debug(
                "Using xpath -> %s to narrow down the replacement",
                replacement["xpath"],
            )
            if "setting" in replacement:
                logger.debug(
                    "Looking up setting -> %s in XML element",
                    replacement["setting"],
                )
            if "assoc_elem" in replacement:
                logger.debug(
                    "Looking up assoc element -> %s in XML element",
                    replacement["assoc_elem"],
                )
        else:  # we have a simple "search & replace" replacement
            if not "placeholder" in replacement:
                logger.error(
                    "Replacement without an xpath needs a placeholder value but it is not specified. Skipping..."
                )
                continue
            if replacement.get("placeholder") == replacement["value"]:
                logger.debug(
                    "Placeholder and replacement are identical -> %s. Skipping...",
                    replacement["value"],
                )
                continue
            logger.debug(
                "Replace -> %s with -> %s in Transport package -> %s",
                replacement["placeholder"],
                replacement["value"],
                zip_file_folder,
            )

        found = XML.replace_in_xml_files(
            zip_file_folder,
            replacement.get("placeholder"),
            replacement["value"],
            replacement.get("xpath"),
            replacement.get("setting"),
            replacement.get("assoc_elem"),
        )
        if found:
            logger.debug(
                "Replacement -> %s has been completed successfully for Transport package -> %s",
                replacement,
                zip_file_folder,
            )
            modified = True
        else:
            logger.warning(
                "Replacement -> %s not found in Transport package -> %s",
                replacement,
                zip_file_folder,
            )

    if not modified:
        logger.warning(
            "None of the specified replacements have been found in Transport package -> %s. No need to create a new transport package.",
            zip_file_folder,
        )
        return False

    # Create the new zip file and add all files from the directory to it
    new_zip_file_path = (
        os.path.dirname(zip_file_path) + "/new_" + os.path.basename(zip_file_path)
    )
    logger.debug(
        "Content of transport -> '%s' has been modified - repacking to new zip file -> %s",
        zip_file_folder,
        new_zip_file_path,
    )
    with zipfile.ZipFile(new_zip_file_path, "w", zipfile.ZIP_DEFLATED) as zip_ref:
        for subdir, _, files in os.walk(
            zip_file_folder
        ):  # 2nd parameter is not used, thus using _ instead of dirs
            for file in files:
                file_path = os.path.join(subdir, file)
                rel_path = os.path.relpath(file_path, zip_file_folder)
                zip_ref.write(file_path, arcname=rel_path)

    # Close the new zip file and delete the temporary directory
    zip_ref.close()
    old_zip_file_path = (
        os.path.dirname(zip_file_path) + "/old_" + os.path.basename(zip_file_path)
    )
    logger.debug(
        "Rename orginal transport zip file -> '%s' to -> '%s'",
        zip_file_path,
        old_zip_file_path,
    )
    os.rename(zip_file_path, old_zip_file_path)
    logger.debug(
        "Rename new transport zip file -> '%s' to -> '%s'",
        new_zip_file_path,
        zip_file_path,
    )
    os.rename(new_zip_file_path, zip_file_path)

    # Return the path to the new zip file
    return True

request_download_header()

Deliver the request header used for the CRUD REST API calls. Consists of Cookie + Form Headers (see global vasriable)

Return: dict: request header values

Source code in pyxecm/otcs.py
def request_download_header(self) -> dict:
    """Deliver the request header used for the CRUD REST API calls.
       Consists of Cookie + Form Headers (see global vasriable)

    Args:
        None.
    Return:
        dict: request header values
    """

    # create union of two dicts: cookie and headers
    # (with Python 3.9 this would be easier with the "|" operator)
    request_header = {}
    request_header.update(self.cookie())
    request_header.update(REQUEST_DOWNLOAD_HEADERS)

    return request_header

request_form_header()

Deliver the request header used for the CRUD REST API calls. Consists of Cookie + Form Headers (see global variable)

Return: dict: request header values

Source code in pyxecm/otcs.py
def request_form_header(self) -> dict:
    """Deliver the request header used for the CRUD REST API calls.
       Consists of Cookie + Form Headers (see global variable)

    Args:
        None.
    Return:
        dict: request header values
    """

    # create union of two dicts: cookie and headers
    # (with Python 3.9 this would be easier with the "|" operator)
    request_header = {}
    request_header.update(self.cookie())
    request_header.update(REQUEST_FORM_HEADERS)

    return request_header

request_json_header()

Deliver the request header for REST calls that require content type application/json. Consists of Cookie + Json Headers (see global variable)

Return: dict: request header values

Source code in pyxecm/otcs.py
def request_json_header(self) -> dict:
    """Deliver the request header for REST calls that require content type application/json.
       Consists of Cookie + Json Headers (see global variable)

    Args:
        None.
    Return:
        dict: request header values
    """

    # create union of two dicts: cookie and headers
    # (with Python 3.9 this would be easier with the "|" operator)
    request_header = {}
    request_header.update(self.cookie())
    request_header.update(REQUEST_JSON_HEADERS)

    return request_header

rest_url()

Returns the REST URL of Extended ECM

Returns:

Name Type Description
str str

REST URL

Source code in pyxecm/otcs.py
def rest_url(self) -> str:
    """Returns the REST URL of Extended ECM

    Returns:
        str: REST URL
    """
    return self.config()["restUrl"]

restore_node(node_id)

Restore an item from the recycle bin (undo deletion)

Parameters:

Name Type Description Default
node_id int | list

ID(s) of the node(s) to be restored

required
Results

dict | None: dictionary include key 'success' with the successful restored IDs

Example

{ 'failure': { 'errors': {}, 'ids': [...] }, 'success': { 'ids': [...] } }

Source code in pyxecm/otcs.py
def restore_node(self, node_id: int | list) -> dict | None:
    """Restore an item from the recycle bin (undo deletion)

    Args:
        node_id (int | list): ID(s) of the node(s) to be restored

    Results:
        dict | None: dictionary include key 'success' with the successful restored IDs

    Example:
        {
            'failure': {
                'errors': {}, 'ids': [...]
            },
            'success': {
                'ids': [...]
            }
        }
    """

    request_url = self.config()["recycleBinUrl"] + "/nodes/restore"
    request_header = self.request_form_header()

    if isinstance(node_id, list):
        restore_data = {"ids": node_id}
    else:
        restore_data = {"ids": [node_id]}

    logger.debug(
        "Restore node(s) with ID(s) -> %s from recycle bin; calling -> %s",
        str(node_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=restore_data,
        timeout=None,
        failure_message="Failed to restore node(s) with ID(s) -> {} from the recycle bin".format(
            node_id
        ),
    )

run_web_report(nickname, web_report_parameters=None)

Run a Web Report that is identified by its nick name.

Parameters:

Name Type Description Default
nickname str

nickname of the Web Reports node.

required
web_report_parameters dict

Parameters of the Web Report (names + value pairs)

None

Returns: dict: Response of the run Web Report request or None if the Web Report execution has failed.

Source code in pyxecm/otcs.py
def run_web_report(
    self, nickname: str, web_report_parameters: dict | None = None
) -> dict | None:
    """Run a Web Report that is identified by its nick name.

    Args:
        nickname (str): nickname of the Web Reports node.
        web_report_parameters (dict): Parameters of the Web Report (names + value pairs)
    Returns:
        dict: Response of the run Web Report request or None if the Web Report execution has failed.
    """

    # Avoid linter warning W0102:
    if web_report_parameters is None:
        web_report_parameters = {}

    request_url = self.config()["webReportsUrl"] + "/" + nickname
    request_header = self.request_form_header()

    logger.debug(
        "Running Web Report with nickname -> %s; calling -> %s",
        nickname,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=web_report_parameters,
        timeout=None,
        failure_message="Failed to run web report with nickname -> '{}'".format(
            nickname
        ),
    )

search(search_term, look_for='complexQuery', modifier='', slice_id=0, query_id=0, template_id=0, limit=100, page=1)

Search for a search term.

Parameters:

Name Type Description Default
search_term str), e.g. "test or OTSubType

189"

required
look_for str

'allwords', 'anywords', 'exactphrase', and 'complexquery'. If not specified, it defaults to 'complexQuery'.

'complexQuery'
modifier str

'synonymsof', 'relatedto', 'soundslike', 'wordbeginswith', and 'wordendswith'. If not specified or specify any value other than the available options, it will be ignored.

''
slice_id int

ID of an existing search slice

0
query_id int

ID of an saved search query

0
template_id int

ID of an saved search template

0
limit int

maximum number of results (default = 100)

100
page int

number of result page (default = 1 = 1st page)

1

Returns: dict: search response or None if the search fails.

Source code in pyxecm/otcs.py
def search(
    self,
    search_term: str,
    look_for: str = "complexQuery",
    modifier: str = "",
    slice_id: int = 0,
    query_id: int = 0,
    template_id: int = 0,
    limit: int = 100,
    page: int = 1,
) -> dict | None:
    """Search for a search term.

    Args:
        search_term (str), e.g. "test or OTSubType: 189"
        look_for (str, optional): 'allwords', 'anywords', 'exactphrase', and 'complexquery'.
                                  If not specified, it defaults to 'complexQuery'.
        modifier (str, optional): 'synonymsof', 'relatedto', 'soundslike', 'wordbeginswith',
                                  and 'wordendswith'.
                                  If not specified or specify any value other than the available options,
                                  it will be ignored.
        slice_id (int, optional): ID of an existing search slice
        query_id (int, optional): ID of an saved search query
        template_id (int, optional): ID of an saved search template
        limit (int, optional): maximum number of results (default = 100)
        page (int, optional): number of result page (default = 1 = 1st page)
    Returns:
        dict: search response or None if the search fails.
    """

    search_post_body = {
        "where": search_term,
        "lookfor": look_for,
        "page": page,
        "limit": limit,
    }

    if modifier:
        search_post_body["modifier"] = modifier
    if slice_id > 0:
        search_post_body["slice_id"] = slice_id
    if query_id > 0:
        search_post_body["query_id"] = query_id
    if template_id > 0:
        search_post_body["template_id"] = template_id

    request_url = self.config()["searchUrl"]
    request_header = self.request_form_header()

    logger.debug("Search for term -> %s; calling -> %s", search_term, request_url)

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=search_post_body,
        timeout=None,
        failure_message="Failed to search for term -> '{}'".format(search_term),
    )

search_user(value, field='where_name')

Find a user based on search criteria.

Parameters:

Name Type Description Default
value str

field value

required
field str

user field to search with (where_name, where_first_name, where_last_name)

'where_name'

Returns: dict: User information or None if the user couldn't be found (e.g. because it doesn't exist).

Example response:
{
    'collection': {
        'paging': {...},
        'sorting': {...}
    },
    'links': {
        'data': {...}
    },
    'results': [
        {
            'data': {
                'properties': {
                    'birth_date': None,
                    'business_email': 'dfoxhoven@M365x61936377.onmicrosoft.com',
                    'business_fax': None,
                    'business_phone': None,
                    'cell_phone': None,
                    'deleted': False,
                    'display_language': None,
                    'first_name': 'Deke',
                    'gender': None,
                    'group_id': 8005,
                    'home_address_1': None,
                    'home_address_2': None,
                    'home_fax': None,
                    'home_phone': None,
                    'id': 8562,
                    'initials': 'DF',
                    'last_name': 'Foxhoven',
                    'middle_name': None,
                    'name': 'dfoxhoven',
                    'name_formatted': 'Deke Foxhoven',
                    ...
                }
            }
        }
    ]
}
Source code in pyxecm/otcs.py
def search_user(self, value: str, field: str = "where_name") -> dict | None:
    """Find a user based on search criteria.

    Args:
        value (str): field value
        field (str): user field to search with (where_name, where_first_name, where_last_name)
    Returns:
        dict: User information or None if the user couldn't be found (e.g. because it doesn't exist).

        Example response:
        {
            'collection': {
                'paging': {...},
                'sorting': {...}
            },
            'links': {
                'data': {...}
            },
            'results': [
                {
                    'data': {
                        'properties': {
                            'birth_date': None,
                            'business_email': 'dfoxhoven@M365x61936377.onmicrosoft.com',
                            'business_fax': None,
                            'business_phone': None,
                            'cell_phone': None,
                            'deleted': False,
                            'display_language': None,
                            'first_name': 'Deke',
                            'gender': None,
                            'group_id': 8005,
                            'home_address_1': None,
                            'home_address_2': None,
                            'home_fax': None,
                            'home_phone': None,
                            'id': 8562,
                            'initials': 'DF',
                            'last_name': 'Foxhoven',
                            'middle_name': None,
                            'name': 'dfoxhoven',
                            'name_formatted': 'Deke Foxhoven',
                            ...
                        }
                    }
                }
            ]
        }
    """

    request_url = self.config()["membersUrlv2"] + "?" + field + "=" + value
    request_header = self.request_form_header()

    logger.debug(
        "Searching user by field -> %s, value -> %s; calling -> %s",
        field,
        value,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=None,
        failure_message="Cannot find user with field -> {}, value -> {}".format(
            field,
            value,
        ),
    )

set_category_inheritance(node_id, category_id, enable=True)

Set if we want a container item (e.g. a folder or workspace) to inherit categories to sub-items.

Parameters:

Name Type Description Default
node_id int

Node ID of the container item.

required
category_id int

Node ID of the category item.

required
enable bool

Whether the inheritance should be enabled (True) or disabled (False)

True

Returns:

Type Description
dict | None

dict | None: Response of the request or None in case of an error.

Source code in pyxecm/otcs.py
def set_category_inheritance(
    self, node_id: int, category_id: int, enable: bool = True
) -> dict | None:
    """Set if we want a container item (e.g. a folder or workspace) to inherit
       categories to sub-items.

    Args:
        node_id (int): Node ID of the container item.
        category_id (int): Node ID of the category item.
        enable (bool): Whether the inheritance should be enabled (True) or disabled (False)

    Returns:
        dict | None: Response of the request or None in case of an error.
    """

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "/categories/"
        + str(category_id)
        + "/inheritance"
    )
    request_header = self.request_form_header()

    if enable:
        logger.debug(
            "Enable category inheritance for node with ID -> %s and category ID -> %s; calling -> %s",
            str(node_id),
            str(category_id),
            request_url,
        )
        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            timeout=None,
            failure_message="Failed to enable categories inheritance for node ID -> {} and category ID -> {}".format(
                node_id, category_id
            ),
        )
    else:
        logger.debug(
            "Disable category inheritance of node with ID -> %s and category ID -> %s; calling -> %s",
            str(node_id),
            str(category_id),
            request_url,
        )
        return self.do_request(
            url=request_url,
            method="DELETE",
            headers=request_header,
            timeout=None,
            failure_message="Failed to disable categories inheritance for node ID -> {} and category ID -> {}".format(
                node_id, category_id
            ),
        )

set_category_value(node_id, value, category_id, attribute_id, set_id=0, set_row=1)

Set a value to a specific attribute in a category. Categories and have sets (groupings), multi-line sets (matrix), and multi-value attributes (list of values). This method supports all variants.

Parameters:

Name Type Description Default
node_id int

ID of the node

required
value multi - typed

value to be set - can be string or list of strings (for multi-value attributes)

required
category_id int

ID of the category object

required
attribute_id int

ID of the attribute, this should not include the category ID nor an underscore but the plain attribute ID like '10'

required
set_id int

ID of the set. Defaults to 0.

0
set_row int

Row of . Defaults to 1.

1

Returns:

Name Type Description
dict dict | None

REST API response or None if the call fails

Source code in pyxecm/otcs.py
def set_category_value(
    self,
    node_id: int,
    value,
    category_id: int,
    attribute_id: int,
    set_id: int = 0,
    set_row: int = 1,
) -> dict | None:
    """Set a value to a specific attribute in a category. Categories and have sets (groupings), multi-line sets (matrix),
       and multi-value attributes (list of values). This method supports all variants.

    Args:
        node_id (int): ID of the node
        value (multi-typed): value to be set - can be string or list of strings (for multi-value attributes)
        category_id (int):ID of the category object
        attribute_id (int): ID of the attribute, this should not include the category ID nor an underscore but the plain attribute ID like '10'
        set_id (int, optional): ID of the set. Defaults to 0.
        set_row (int, optional): Row of . Defaults to 1.

    Returns:
        dict: REST API response or None if the call fails
    """

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "/categories/"
        + str(category_id)
    )
    request_header = self.request_form_header()

    if set_id:
        logger.debug(
            "Assign value -> '%s' to category with ID -> %s, set ID -> %s, row -> %s, attribute ID -> %s on node with ID -> %s; calling -> %s",
            str(value),
            str(category_id),
            str(set_id),
            str(set_row),
            str(attribute_id),
            str(node_id),
            request_url,
        )
        category_put_data = {
            "category_id": category_id,
            "{}_{}_{}_{}".format(category_id, set_id, set_row, attribute_id): value,
        }
        failure_message = "Failed to set value -> '{}' for category with ID -> {}, set ID -> {}, set row -> {}, attribute ID -> {} on node ID -> {}".format(
            value,
            category_id,
            set_id,
            set_row,
            attribute_id,
            node_id,
        )
    else:
        logger.debug(
            "Assign value -> '%s' to category ID -> %s, attribute ID -> %s on node with ID -> %s; calling -> %s",
            str(value),
            str(category_id),
            str(attribute_id),
            str(node_id),
            request_url,
        )
        category_put_data = {
            "category_id": category_id,
            "{}_{}".format(category_id, attribute_id): value,
        }
        failure_message = "Failed to set value -> '{}' for category with ID -> {}, attribute ID -> {} on node ID -> {}".format(
            value,
            category_id,
            attribute_id,
            node_id,
        )

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data=category_put_data,
        timeout=None,
        failure_message=failure_message,
    )

set_category_values(node_id, category_id, category_data)

Set values of a category. Categories and have sets (groupings), multi-line sets (matrix), and multi-value attributes (list of values). This method supports all variants.

Parameters:

Name Type Description Default
node_id int

ID of the node

required
value multi - typed

value to be set - can be string or list of strings (for multi-value attributes)

required
category_id int

ID of the category object

required
category_data dict

dictionary with category attributes and values

required

Returns:

Name Type Description
dict dict | None

REST API response or None if the call fails

Source code in pyxecm/otcs.py
def set_category_values(
    self,
    node_id: int,
    category_id: int,
    category_data: dict,
) -> dict | None:
    """Set values of a category. Categories and have sets (groupings), multi-line sets (matrix),
       and multi-value attributes (list of values). This method supports all variants.

    Args:
        node_id (int): ID of the node
        value (multi-typed): value to be set - can be string or list of strings (for multi-value attributes)
        category_id (int):ID of the category object
        category_data (dict): dictionary with category attributes and values

    Returns:
        dict: REST API response or None if the call fails
    """

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "/categories/"
        + str(category_id)
    )
    request_header = self.request_form_header()

    category_put_data = {"category_id": category_id}
    category_put_data.update(category_data)

    logger.debug(
        "Set values -> %s for category ID -> %s on node -> %s...",
        category_data,
        category_id,
        node_id,
    )

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data=category_put_data,
        timeout=None,
        failure_message="Failed to set values -> '{}' for category with ID -> {}, on node ID -> {}".format(
            category_data, category_id, node_id
        ),
    )

set_credentials(username='admin', password='')

Set the credentials for Extended ECM based on username and password.

Parameters:

Name Type Description Default
username str

Username. Defaults to "admin".

'admin'
password str

Password of the user. Defaults to "".

''
Source code in pyxecm/otcs.py
def set_credentials(self, username: str = "admin", password: str = ""):
    """Set the credentials for Extended ECM based on username and password.

    Args:
        username (str, optional): Username. Defaults to "admin".
        password (str, optional): Password of the user. Defaults to "".
    """

    self.config()["username"] = username
    self.config()["password"] = password

set_hostname(hostname)

Sets the hostname of Extended ECM

Parameters:

Name Type Description Default
hostname str

new hostname

required
Source code in pyxecm/otcs.py
def set_hostname(self, hostname: str):
    """Sets the hostname of Extended ECM

    Args:
        hostname (str): new hostname
    """
    self.config()["hostname"] = hostname

set_node_nickname(node_id, nickname, show_error=False)

Assign a nickname to an Extended ECM node (e.g. workspace)

Parameters:

Name Type Description Default
nickname str

Nickname of the node.

required
show_error bool

treat as error if node is not found

False

Returns: dict: Node information or None if no node with this nickname is found.

Source code in pyxecm/otcs.py
def set_node_nickname(
    self, node_id: int, nickname: str, show_error: bool = False
) -> dict | None:
    """Assign a nickname to an Extended ECM node (e.g. workspace)

    Args:
        nickname (str): Nickname of the node.
        show_error (bool): treat as error if node is not found
    Returns:
        dict: Node information or None if no node with this nickname is found.
    """

    if not nickname:
        return None

    nickname = nickname.replace("-", "_")
    nickname = nickname.replace(":", "_")
    nickname = nickname.replace("/", "_")
    nickname = nickname.replace(" ", "_")

    nickname_put_body = {"nickname": nickname}

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/nicknames"
    request_header = self.request_form_header()

    logger.debug(
        "Assign nickname -> '%s' to node with ID -> %s; calling -> %s",
        nickname,
        node_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data=nickname_put_body,
        timeout=None,
        warning_message="Cannot assign nickname -> '{}' to node ID -> {}. Maybe the nickname is already in use or the node does not exist.".format(
            nickname, node_id
        ),
        failure_message="Failed to assign nickname -> '{}' to node ID -> {}".format(
            nickname, node_id
        ),
        show_error=show_error,
    )

set_workspace_reference(workspace_id, external_system_id=None, bo_type=None, bo_id=None, show_error=True)

Set reference of workspace to a business object in an external system

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace

required
external_system_id str

Identifier of the external system (None if no external system)

None
bo_type str

Business object type (None if no external system)

None
bo_id str

Business object identifier / key (None if no external system)

None
show_error bool

Log an error if workspace cration fails. Otherwise log a warning.

True
Source code in pyxecm/otcs.py
def set_workspace_reference(
    self,
    workspace_id: int,
    external_system_id: str | None = None,
    bo_type: str | None = None,
    bo_id: str | None = None,
    show_error: bool = True,
):
    """Set reference of workspace to a business object in an external system

    Args:
        workspace_id (int): ID of the workspace
        external_system_id (str, optional): Identifier of the external system (None if no external system)
        bo_type (str, optional): Business object type (None if no external system)
        bo_id (str, optional): Business object identifier / key (None if no external system)
        show_error (bool, optional): Log an error if workspace cration fails. Otherwise log a warning.
    """

    request_url = (
        self.config()["businessWorkspacesUrl"]
        + "/"
        + str(workspace_id)
        + "/workspacereferences"
    )
    request_header = self.request_form_header()

    if not external_system_id or not bo_type or not bo_id:
        logger.error(
            "Cannot update workspace reference - required Business Object information is missing!"
        )
        return None

    logger.debug(
        "Update workspace reference of workspace ID -> %s with business object connection -> (%s, %s, %s); calling -> %s",
        str(workspace_id),
        external_system_id,
        bo_type,
        bo_id,
        request_url,
    )

    workspace_put_data = {
        "ext_system_id": external_system_id,
        "bo_type": bo_type,
        "bo_id": bo_id,
    }

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data=workspace_put_data,
        timeout=None,
        warning_message="Cannot update reference for workspace ID -> {} with business object connection -> ({}, {}, {})".format(
            workspace_id, external_system_id, bo_type, bo_id
        ),
        failure_message="Failed to update reference for workspace ID -> {} with business object connection -> ({}, {}, {})".format(
            workspace_id, external_system_id, bo_type, bo_id
        ),
        show_error=show_error,
    )

unpack_transport_package(package_id, workbench_id)

Unpack an existing Transport Package into an existing Workbench.

Parameters:

Name Type Description Default
package_id int

ID of package to be unpacked

required
workbench_id int

ID of target workbench

required

Returns: dict: Unpack response or None if the unpacking fails.

Source code in pyxecm/otcs.py
def unpack_transport_package(
    self, package_id: int, workbench_id: int
) -> dict | None:
    """Unpack an existing Transport Package into an existing Workbench.

    Args:
        package_id (int): ID of package to be unpacked
        workbench_id (int): ID of target workbench
    Returns:
        dict: Unpack response or None if the unpacking fails.
    """

    unpack_package_post_data = {"workbench_id": workbench_id}

    request_url = self.config()["nodesUrlv2"] + "/" + str(package_id) + "/unpack"
    request_header = self.request_form_header()

    logger.debug(
        "Unpack transport package with ID -> %s into workbench with ID -> %s; calling -> %s",
        str(package_id),
        str(workbench_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=unpack_package_post_data,
        timeout=None,
        failure_message="Failed to unpack package with ID -> {} to workbench with ID -> {}".format(
            package_id, workbench_id
        ),
    )

update_draft_process(draftprocess_id, title='', due_date='', values=None)

Update a draft process with values. These can either be given via dedicated parameters like title and due_date or with a generic value dictionary.

Parameters:

Name Type Description Default
draftprocess_id int

ID of the draft process that has been created before with create_draft_process()

required
title str

Title of the process

''
due_date str

due date for the process. Defaults to "".

''
values dict | None

values for workflow attributes. Defaults to None.

None

Returns:

Type Description
dict | None

dict | None: Respinse of the REST API or None in case of an error.

Source code in pyxecm/otcs.py
def update_draft_process(
    self,
    draftprocess_id: int,
    title: str = "",
    due_date: str = "",
    values: dict | None = None,
) -> dict | None:
    """Update a draft process with values. These can either be given via dedicated parameters
       like title and due_date or with a generic value dictionary.

    Args:
        draftprocess_id (int): ID of the draft process that has been created before with create_draft_process()
        title (str): Title of the process
        due_date (str, optional): due date for the process. Defaults to "".
        values (dict | None, optional): values for workflow attributes. Defaults to None.

    Returns:
        dict | None: Respinse of the REST API or None in case of an error.
    """

    request_url = self.config()["draftProcessUrl"] + "/" + str(draftprocess_id)
    request_header = self.request_form_header()

    logger.debug(
        "Update draft process with ID -> %s with these values -> %s; calling -> %s",
        str(draftprocess_id),
        str(values),
        request_url,
    )

    if not values:
        values = {}

    if title:
        values["WorkflowForm_Title"] = title
    if due_date:
        values["WorkflowForm_WorkflowDueDate"] = due_date

    update_draft_process_body_put_data = {
        "action": "formUpdate",
        "values": values,
    }

    # this call needs a "body" tag around the
    # actual payload - otherwise it will return just "None"
    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data={"body": json.dumps(update_draft_process_body_put_data)},
        timeout=None,
        failure_message="Failed to update draft process with ID -> {} with these values -> {}".format(
            draftprocess_id, values
        ),
    )

update_item(node_id, parent_id=None, item_name=None, item_description=None, category_data=None, external_modify_date=None, external_create_date=None)

Update an Extended ECM item (parent, name, description, metadata). Changing the parent ID is a move operation. If parent ID = 0 or None the item will not be moved.

Parameters:

Name Type Description Default
node_id int

ID of the node

required
parent_id int | None

node ID of the new parent (in case of a move operation)

None
item_name str | None

new name of the item

None
item_description str | None

new description of the item

None
category_data dict | None

new category and attributes values

None

Returns: dict: Response of the update item request or None if the REST call has failed.

Source code in pyxecm/otcs.py
def update_item(
    self,
    node_id: int,
    parent_id: int | None = None,
    item_name: str | None = None,
    item_description: str | None = None,
    category_data: dict | None = None,
    external_modify_date: str | None = None,
    external_create_date: str | None = None,
) -> dict | None:
    """Update an Extended ECM item (parent, name, description, metadata). Changing the parent ID is
       a move operation. If parent ID = 0 or None the item will not be moved.

    Args:
        node_id (int): ID of the node
        parent_id (int | None, optional): node ID of the new parent (in case of a move operation)
        item_name (str | None, optional): new name of the item
        item_description (str | None, optional): new description of the item
        category_data (dict | None): new category and attributes values
        external_create_date (str, optional) value of the source system in format 2024-06-24
        external_modify_date (str, optional) value of the source system in format 2024-06-24
    Returns:
        dict: Response of the update item request or None if the REST call has failed.
    """

    update_item_put_data = {}

    if item_name:
        # this is a rename operation
        update_item_put_data["name"] = item_name
    if item_description:
        # this is a change description operation
        update_item_put_data["description"] = item_description
    if parent_id:
        # this is a move operation
        update_item_put_data["parent_id"] = parent_id

    # Set external dates if provided:
    if external_create_date:
        update_item_put_data["external_create_date"] = external_create_date
    if external_modify_date:
        update_item_put_data["external_modify_date"] = external_modify_date

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id)
    request_header = self.request_form_header()

    logger.debug(
        "Update item -> '%s' (%s) with data -> %s; calling -> %s",
        item_name,
        node_id,
        str(update_item_put_data),
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data={"body": json.dumps(update_item_put_data)},
        timeout=None,
        failure_message="Failed to update item -> '{}' ({})".format(
            item_name, node_id
        ),
    )

    if response and category_data:
        for category in category_data:
            response = self.set_category_values(
                node_id=node_id,
                category_id=category,
                category_data=category_data[category],
            )

    return response

update_process_task(process_id, subprocess_id=None, task_id=1, values=None, action='formUpdate', custom_action='', comment='')

Update a process with values in a task. This method needs to be called with the user that has the task in its inbox (My ToDo - Workflows). It can update the task data (formUpdate) and/or send on the task to the next workflow step (action or custom_action).

TODO: this method is currently untested.

Parameters:

Name Type Description Default
process_id int

ID of the draft process that has been created before with create_draft_process()

required
task_id int

ID of the task. Default is 1.

1
values dict | None

values for workflow attributes. Defaults to None. It is only used if action = "formUpdate".

None
action str

the name of the action to process. The default is "formUpdate".

'formUpdate'
custom_action str

Here we can have custom actions like "Approve" or "Reject". if "custom_action" is not None then the "action" parameter is ignored.

''
comment str

the comment given with the action

''

Returns:

Type Description
dict | None

dict | None: Respinse of the REST API or None in case of an error.

Source code in pyxecm/otcs.py
def update_process_task(
    self,
    process_id: int,
    subprocess_id: int | None = None,
    task_id: int = 1,
    values: dict | None = None,
    action: str = "formUpdate",
    custom_action: str = "",
    comment: str = "",
) -> dict | None:
    """Update a process with values in a task. This method needs to be called with the user
       that has the task in its inbox (My ToDo - Workflows). It can update the task data (formUpdate)
       and/or send on the task to the next workflow step (action or custom_action).

        TODO: this method is currently untested.

    Args:
        process_id (int): ID of the draft process that has been created before with create_draft_process()
        task_id (int, optional): ID of the task. Default is 1.
        values (dict | None, optional): values for workflow attributes. Defaults to None. It is only
                                        used if action = "formUpdate".
        action (str, optional): the name of the action to process. The default is "formUpdate".
        custom_action (str, optional): Here we can have custom actions like "Approve" or "Reject".
                                       if "custom_action" is not None then the "action" parameter is ignored.
        comment (str, optional): the comment given with the action

    Returns:
        dict | None: Respinse of the REST API or None in case of an error.
    """

    if not action and not custom_action:
        logger.error(
            "Either 'action' or 'custom_action' is required for updating a process task!"
        )
        return None

    if subprocess_id is None:
        subprocess_id = process_id

    request_url = (
        self.config()["processUrl"]
        + "/"
        + str(process_id)
        + "/subprocesses/"
        + str(subprocess_id)
        + "/tasks/"
        + str(task_id)
    )
    request_header = self.request_form_header()

    if values:
        logger.debug(
            "Update task with ID -> %s of process with ID -> %s with these values -> %s; calling -> %s",
            str(task_id),
            str(process_id),
            str(values),
            request_url,
        )

    if not values:
        values = {}

    if not custom_action:
        update_process_task_body_put_data = {
            "action": action,
        }
        if action == "formUpdate":
            update_process_task_body_put_data["values"] = values
        logger.debug(
            "Execute action -> '%s' for process with ID -> %s",
            action,
            str(process_id),
        )
    else:  # we have a custom action:
        update_process_task_body_put_data = {
            "custom_action": custom_action,
        }
        logger.debug(
            "Execute custom action -> '%s' for process with ID -> %s",
            custom_action,
            str(process_id),
        )
    if comment:
        update_process_task_body_put_data["comment"] = comment

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data={"body": json.dumps(update_process_task_body_put_data)},
        timeout=None,
        failure_message="Failed to update task with ID -> {} of process with ID -> {} with these values -> {}".format(
            task_id, process_id, values
        ),
    )

update_records_management_codes(rm_codes)

Update Records Management Codes. These are the most basic data types of the Records Management configuration and required to create RSIs and other higher-level Records Management configurations THIS METHOD IS CURRENTLY NOT WORKING

Parameters:

Name Type Description Default
rm_codes dict

Codes to be updated

required

Returns: dict: RSI data or None if the request fails.

Source code in pyxecm/otcs.py
def update_records_management_codes(self, rm_codes: dict) -> dict | None:
    """Update Records Management Codes. These are the most basic data types of
       the Records Management configuration and required to create RSIs and
       other higher-level Records Management configurations
       THIS METHOD IS CURRENTLY NOT WORKING

    Args:
        rm_codes (dict): Codes to be updated
    Returns:
        dict: RSI data or None if the request fails.
    """

    update_rm_codes_post_data = {}

    request_url = self.config()["recordsManagementUrl"] + "/rmcodes"
    request_header = self.request_form_header()

    logger.debug(
        "Update Records Management codes -> %s; calling -> %s",
        str(rm_codes),
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=update_rm_codes_post_data,
        timeout=None,
        failure_message="Failed to update Records Management codes with -> {}".format(
            rm_codes
        ),
    )

    if response and "results" in response and response["results"]:
        return response["results"]["data"]

    return None

update_user(user_id, field, value)

Update a defined field for a user.

Parameters:

Name Type Description Default
user_id int

ID of the user

required
value str

field value

required
field str

user field

required

Returns: dict: User information or None if the user couldn't be updated (e.g. because it doesn't exist).

Source code in pyxecm/otcs.py
def update_user(self, user_id: int, field: str, value: str) -> dict | None:
    """Update a defined field for a user.

    Args:
        user_id (int): ID of the user
        value (str): field value
        field (str): user field
    Returns:
        dict: User information or None if the user couldn't be updated (e.g. because it doesn't exist).
    """

    user_put_body = {field: value}

    request_url = self.config()["membersUrlv2"] + "/" + str(user_id)
    request_header = self.request_form_header()

    logger.debug(
        "Updating user with ID -> %s, field -> %s, value -> %s; calling -> %s",
        str(user_id),
        field,
        value,
        request_url,
    )
    logger.debug("User Attributes -> %s", str(user_put_body))

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data=user_put_body,
        timeout=None,
        failure_message="Failed to update user with ID -> {}".format(user_id),
    )

update_user_photo(user_id, photo_id)

Update a user with a profile photo (which must be an existing node).

Parameters:

Name Type Description Default
user_id int

ID of the user

required
photo_id int

Node ID of the photo

required

Returns: dict: Node information or None if photo node is not found.

Source code in pyxecm/otcs.py
def update_user_photo(self, user_id: int, photo_id: int) -> dict | None:
    """Update a user with a profile photo (which must be an existing node).

    Args:
        user_id (int): ID of the user
        photo_id (int): Node ID of the photo
    Returns:
        dict: Node information or None if photo node is not found.
    """

    update_user_put_body = {"photo_id": photo_id}

    request_url = self.config()["membersUrl"] + "/" + str(user_id)
    request_header = self.request_form_header()

    logger.debug(
        "Update user ID -> %s with photo ID -> %s; calling -> %s",
        user_id,
        photo_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data=update_user_put_body,
        timeout=None,
        failure_message="Failed to update user with ID -> {}".format(user_id),
    )

update_user_profile(field, value, config_section='SmartUI')

Update a defined field for a user profile. IMPORTANT: this method needs to be called by the authenticated user

Parameters:

Name Type Description Default
field str

user profile field

required
value str

new field value

required
config_section str

name of the config section. Possible config_section values: * SmartUI * General * Colors * ContentIntelligence * Discussion * Follow Up * Template Workspaces * Workflow * XECMGOVSettings * CommunitySettings * RecMan * PhysObj

'SmartUI'

Returns: dict: User information or None if the user couldn't be updated (e.g. because it doesn't exist).

Source code in pyxecm/otcs.py
def update_user_profile(
    self, field: str, value: str, config_section: str = "SmartUI"
) -> dict | None:
    """Update a defined field for a user profile.
       IMPORTANT: this method needs to be called by the authenticated user

    Args:
        field (str): user profile field
        value (str): new field value
        config_section (str, optional): name of the config section. Possible config_section values:
                                        * SmartUI
                                        * General
                                        * Colors
                                        * ContentIntelligence
                                        * Discussion
                                        * Follow Up
                                        * Template Workspaces
                                        * Workflow
                                        * XECMGOVSettings
                                        * CommunitySettings
                                        * RecMan
                                        * PhysObj
    Returns:
        dict: User information or None if the user couldn't be updated
              (e.g. because it doesn't exist).
    """

    user_profile_put_body = {config_section: {field: value}}

    request_url = self.config()["membersUrlv2"] + "/preferences"
    request_header = self.request_form_header()

    logger.debug(
        "Updating profile for current user, field -> %s, value -> %s; calling -> %s",
        field,
        value,
        request_url,
    )
    logger.debug("User Attributes -> %s", str(user_profile_put_body))

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data={"body": json.dumps(user_profile_put_body)},
        timeout=None,
        failure_message="Failed to update profile of current user",
    )

update_workspace(workspace_id, workspace_name=None, workspace_description=None, category_data=None, external_system_id=None, bo_type=None, bo_id=None, external_modify_date=None, external_create_date=None, show_error=True)

Update an existing business workspace. This is a wrapper method to update a combination of workspace name / description, workspace reference, and workspace metadata

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace

required
workspace_name str

New Name of the workspace

None
workspace_description str

New Description of the workspace

None
category_data dict

Category and attributes

None
external_system_id str

Identifier of the external system (None if no external system)

None
bo_type str

Business object type (None if no external system)

None
bo_id str

Business object identifier / key (None if no external system)

None
show_error bool

Log an error if workspace cration fails. Otherwise log a warning.

True

Returns: dict: Response of the REST API call or None if the request fails.

Source code in pyxecm/otcs.py
def update_workspace(
    self,
    workspace_id: int,
    workspace_name: str | None = None,
    workspace_description: str | None = None,
    category_data: dict | None = None,
    external_system_id: str | None = None,
    bo_type: str | None = None,
    bo_id: str | None = None,
    external_modify_date: str | None = None,
    external_create_date: str | None = None,
    show_error: bool = True,
) -> bool:
    """Update an existing business workspace. This is a wrapper method to update
       a combination of workspace name / description, workspace reference, and workspace metadata

    Args:
        workspace_id (int): ID of the workspace
        workspace_name (str): New Name of the workspace
        workspace_description (str): New Description of the workspace
        category_data (dict): Category and attributes
        external_system_id (str, optional): Identifier of the external system (None if no external system)
        bo_type (str, optional): Business object type (None if no external system)
        bo_id (str, optional): Business object identifier / key (None if no external system)
        show_error (bool, optional): Log an error if workspace cration fails. Otherwise log a warning.
    Returns:
        dict: Response of the REST API call or None if the request fails.
    """

    # Should we connect this workspace to a business application / external system?
    if external_system_id and bo_type and bo_id:
        response = self.set_workspace_reference(
            workspace_id=workspace_id,
            external_system_id=external_system_id,
            bo_type=bo_type,
            bo_id=bo_id,
            show_error=show_error,
        )
        if not response:
            return False

    # Should we change the name and/or the description or the category data of this workspace?
    if workspace_name or workspace_description:
        response = self.update_item(
            node_id=workspace_id,
            item_name=workspace_name,
            item_description=workspace_description,
            category_data=category_data,
            external_create_date=external_create_date,
            external_modify_date=external_modify_date,
        )
        if not response:
            return False

    return True

update_workspace_aviator(workspace_id, status)

Enable or disable the Content Aviator for a workspace

Parameters:

Name Type Description Default
workspace_id int

node ID of the workspace

required
status bool

True = enable, False = disable Content Aviator for this workspace

required

Returns: dict: REST response or None if the REST call fails.

Source code in pyxecm/otcs.py
def update_workspace_aviator(
    self,
    workspace_id: int,
    status: bool,
) -> dict | None:
    """Enable or disable the Content Aviator for a workspace

    Args:
        workspace_id (int): node ID of the workspace
        status (bool): True = enable, False = disable Content Aviator for this workspace
    Returns:
        dict: REST response or None if the REST call fails.
    """

    aviator_status_put_data = {
        "enabled": status,
    }

    request_url = self.config()["aiUrl"] + "/{}".format(workspace_id)
    request_header = self.request_form_header()

    if status is True:
        logger.debug(
            "Enable Content Aviator for workspace with ID -> %s; calling -> %s",
            str(workspace_id),
            request_url,
        )
    else:
        logger.debug(
            "Disable Content Aviator for workspace with ID -> %s; calling -> %s",
            str(workspace_id),
            request_url,
        )

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data=aviator_status_put_data,
        timeout=None,
        failure_message="Failed to change status for Content Aviator on workspace with ID -> {}".format(
            workspace_id
        ),
    )

update_workspace_icon(workspace_id, file_path, file_mimetype='image/*')

Update a workspace with a with a new icon (which is uploaded).

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace

required
file_path str

path + filename of icon file

required
file_mimetype str

mimetype of the image

'image/*'

Returns: dict: Node information or None if REST call fails.

Source code in pyxecm/otcs.py
def update_workspace_icon(
    self, workspace_id: int, file_path: str, file_mimetype: str = "image/*"
) -> dict | None:
    """Update a workspace with a with a new icon (which is uploaded).

    Args:
        workspace_id (int): ID of the workspace
        file_path (str): path + filename of icon file
        file_mimetype (str, optional): mimetype of the image
    Returns:
        dict: Node information or None if REST call fails.
    """

    if not os.path.exists(file_path):
        logger.error("Workspace icon file does not exist -> %s", file_path)
        return None

    update_workspace_icon_post_body = {
        "file_content_type": file_mimetype,
        "file_filename": os.path.basename(file_path),
    }

    upload_workspace_icon_post_files = [
        (
            "file",
            (
                f"{os.path.basename(file_path)}",
                open(file_path, "rb"),
                file_mimetype,
            ),
        )
    ]

    request_url = (
        self.config()["businessWorkspacesUrl"] + "/" + str(workspace_id) + "/icons"
    )

    request_header = self.cookie()

    logger.debug(
        "Update icon for workspace ID -> %s with icon file -> %s; calling -> %s",
        str(workspace_id),
        file_path,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=update_workspace_icon_post_body,
        files=upload_workspace_icon_post_files,
        timeout=None,
        failure_message="Failed to update workspace ID -> {} with new icon -> '{}'".format(
            workspace_id, file_path
        ),
    )

upload_file_to_parent(file_url, file_name, mime_type, parent_id, category_data=None, description='', external_modify_date=None, external_create_date=None, show_error=True)

Fetch a file from a URL or local filesystem and upload it to a Content Server parent (folder).

Parameters:

Name Type Description Default
file_url str

URL to download file or local file

required
file_name str

name of the file

required
mime_type str

mimeType of the file

required
parent_id int

parent (ID) of the file to upload

required
category_data dict

metadata / category data Example: category ID = 12508 { "12508": { "12508_2": "Draft", # Text drop-down "12508_3": 8559, # user ID "12508_4": "2023-05-10", # date "12508_6": 7357, # user ID "12508_7": "2023-05-11", # date "12508_5": True, # checkbox / bool "12508_8": "EN", # text drop-down "12508_9": "MS Word", # text drop-down } }

None
description str

description of the document

''
show_error bool

treat as error if upload has failed (you may not want to show an error if the file already exists)

True

Returns: dict: Upload response or None if the upload fails.

Source code in pyxecm/otcs.py
def upload_file_to_parent(
    self,
    file_url: str,
    file_name: str,
    mime_type: str,
    parent_id: int,
    category_data: dict | None = None,
    description: str = "",
    external_modify_date: str | None = None,
    external_create_date: str | None = None,
    show_error: bool = True,
) -> dict | None:
    """Fetch a file from a URL or local filesystem and upload it to a Content Server parent (folder).

    Args:
        file_url (str): URL to download file or local file
        file_name (str): name of the file
        mime_type (str): mimeType of the file
        parent_id (int): parent (ID) of the file to upload
        category_data (dict): metadata / category data
                                Example: category ID = 12508
                                {
                                    "12508": {
                                        "12508_2": "Draft",         # Text drop-down
                                        "12508_3": 8559,            # user ID
                                        "12508_4": "2023-05-10",    # date
                                        "12508_6": 7357,            # user ID
                                        "12508_7": "2023-05-11",    # date
                                        "12508_5": True,            # checkbox / bool
                                        "12508_8": "EN",            # text drop-down
                                        "12508_9": "MS Word",       # text drop-down
                                    }
                                }
        description (str, optional): description of the document
        external_create_date (str, optional) value of the source system in format 2024-06-24
        external_modify_date (str, optional) value of the source system in format 2024-06-24
        show_error (bool, optional): treat as error if upload has failed
                                     (you may not want to show an error if the file already exists)
    Returns:
        dict: Upload response or None if the upload fails.
    """

    if not file_name:
        logger.error("Missing file name! Cannot upload file.")
        return None

    # Make sure we don't have leading or trailing whitespace:
    file_name = file_name.strip()

    if file_url.startswith("http"):
        # Download file from remote location specified by the file_url parameter
        # this must be a public place without authentication:
        logger.debug("Download file from URL -> %s", file_url)

        try:
            response = requests.get(url=file_url, timeout=1200)
            response.raise_for_status()
        except requests.exceptions.HTTPError as errh:
            logger.error("Http Error -> %s", errh.strerror)
            return None
        except requests.exceptions.ConnectionError as errc:
            logger.error("Error Connecting -> %s", errc.strerror)
            return None
        except requests.exceptions.Timeout as errt:
            logger.error("Timeout Error -> %s", errt.strerror)
            return None
        except requests.exceptions.RequestException as err:
            logger.error("Request error -> %s", err.strerror)
            return None

        logger.debug(
            "Successfully downloaded file -> %s; status code -> %s",
            file_url,
            response.status_code,
        )
        file_content = response.content

    elif os.path.exists(file_url):
        logger.debug("Uploading local file -> %s", file_url)
        file_content = open(file=file_url, mode="rb")

    else:
        logger.warning("Cannot access -> %s", file_url)
        return None

    upload_post_data = {
        "type": str(144),
        "name": file_name,
        "parent_id": str(parent_id),
        "external_create_date": external_create_date,
        "external_modify_date": external_modify_date,
    }

    if description:
        upload_post_data["description"] = description

    if not mime_type:
        mime_type, _ = mimetypes.guess_type(file_url)

    if not mime_type and magic_installed:
        try:
            mime = magic.Magic(mime=True)
            mime_type = mime.from_file(file_url)
        except Exception:
            logger.error(
                "Mime type for document -> '%s' could not be identified for parent ID -> %s",
                file_name,
                str(parent_id),
            )

    upload_post_files = [("file", (f"{file_name}", file_content, mime_type))]

    request_url = self.config()["nodesUrlv2"]

    # When we upload files using the 'files' parameter, the request must be encoded
    # as multipart/form-data, which allows binary data (like files) to be sent along
    # with other form data.
    # The requests library sets this header correctly fwhen the 'files' parameter is provided.
    # So we just put the cookie in the header and trust the request library to add
    # the Content-Type = multipart/form-data :
    request_header = self.cookie()

    logger.debug(
        "Upload file -> '%s' with mime type -> '%s' to parent with ID -> %s; calling -> %s",
        file_name,
        mime_type,
        str(parent_id),
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=upload_post_data,
        files=upload_post_files,
        timeout=None,
        warning_message="Cannot upload file -> '{}' to parent with ID -> {}. It may already exist.".format(
            file_url, parent_id
        ),
        failure_message="Failed to upload file -> '{}' to parent -> {}".format(
            file_url, parent_id
        ),
        show_error=show_error,
    )

    node_id = self.get_result_value(response, "id")
    if not node_id:
        logger.error("No Node ID found! Cannot set category.")
        return None

    # Update the categories on the documents
    if category_data is not None:
        for category in category_data:
            self.set_category_values(
                node_id=node_id,
                category_id=category,
                category_data=category_data[category],
            )

    return response

upload_file_to_volume(package_url, file_name, mime_type, volume_type)

Fetch a file from a URL or local filesystem and upload it to a Content Server volume.

Parameters:

Name Type Description Default
package_url str

URL to download file

required
file_name str

name of the file

required
mime_type str

mimeType of the file

required
volume_type int

type (ID) of the volume

required

Returns: dict: Upload response or None if the upload fails.

Source code in pyxecm/otcs.py
def upload_file_to_volume(
    self, package_url: str, file_name: str, mime_type: str, volume_type: int
) -> dict | None:
    """Fetch a file from a URL or local filesystem and upload it to a Content Server volume.

    Args:
        package_url (str): URL to download file
        file_name (str): name of the file
        mime_type (str): mimeType of the file
        volume_type (int): type (ID) of the volume
    Returns:
        dict: Upload response or None if the upload fails.
    """

    if package_url.startswith("http"):
        # Download file from remote location specified by the packageUrl
        # this must be a public place without authentication:
        logger.debug("Download transport package from URL -> %s", package_url)

        try:
            package = requests.get(url=package_url, timeout=1200)
            package.raise_for_status()
        except requests.exceptions.HTTPError as errh:
            logger.error("Http Error -> %s", errh.strerror)
            return None
        except requests.exceptions.ConnectionError as errc:
            logger.error("Error Connecting -> %s", errc.strerror)
            return None
        except requests.exceptions.Timeout as errt:
            logger.error("Timeout Error -> %s", errt.strerror)
            return None
        except requests.exceptions.RequestException as err:
            logger.error("Request error -> %s", err.strerror)
            return None

        logger.debug(
            "Successfully downloaded package -> %s; status code -> %s",
            package_url,
            package.status_code,
        )
        file = package.content

    elif os.path.exists(package_url):
        logger.debug("Using local package -> %s", package_url)
        file = open(file=package_url, mode="rb")

    else:
        logger.warning("Cannot access -> %s", package_url)
        return None

    upload_post_data = {"type": str(volume_type), "name": file_name}
    upload_post_files = [("file", (f"{file_name}", file, mime_type))]

    request_url = self.config()["nodesUrlv2"]

    # When we upload files using the 'files' parameter, the request must be encoded
    # as multipart/form-data, which allows binary data (like files) to be sent along
    # with other form data.
    # The requests library sets this header correctly if the 'files' parameter is provided.
    # So we just put the cookie in the header and trust the request library to add
    # the Content-Type = multipart/form-data :
    request_header = self.cookie()

    logger.debug(
        "Upload package -> '%s' with mime type -> '%s'; calling -> %s",
        file_name,
        mime_type,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=upload_post_data,
        files=upload_post_files,
        timeout=None,
        failure_message="Failed to upload file -> '{}' to volume of type -> {}".format(
            package_url, volume_type
        ),
    )

volume_translator(current_node_id, translator, languages, simulate=False)

Experimental code to translate the item names and item descriptions in a given hierarchy. The actual translation is done by a tranlator object. This recursive method just traverses the hierarchy and calls the translate() method of the translator object.

Parameters:

Name Type Description Default
current_node_id int

current node ID to translate

required
translator object

this object needs to be created based on the "Translator" class and passed to this method

required
languages list

list of target languages

required
simulate bool

if True, do not really rename but just traverse and log info. the default is False

False
Source code in pyxecm/otcs.py
def volume_translator(
    self,
    current_node_id: int,
    translator: object,
    languages: list,
    simulate: bool = False,
):
    """Experimental code to translate the item names and item descriptions in a given hierarchy.
       The actual translation is done by a tranlator object. This recursive method just
       traverses the hierarchy and calls the translate() method of the translator object.

    Args:
        current_node_id (int): current node ID to translate
        translator (object): this object needs to be created based on the "Translator" class
                             and passed to this method
        languages (list): list of target languages
        simulate (bool, optional): if True, do not really rename but just traverse and log info.
                                   the default is False
    """
    # Get current node based on the ID:
    current_node = self.get_node(current_node_id)
    current_node_id = self.get_result_value(current_node, "id")

    name = self.get_result_value(current_node, "name")
    description = self.get_result_value(current_node, "description")
    names_multilingual = self.get_result_value(current_node, "name_multilingual")
    descriptions_multilingual = self.get_result_value(
        current_node, "description_multilingual"
    )

    for language in languages:
        if language == "en":
            continue
        # Does the language not exist as metadata language or is it already translated?
        # Then we skip this language:
        if (
            language in names_multilingual
            and names_multilingual["en"]
            and not names_multilingual[language]
        ):
            names_multilingual[language] = translator.translate(
                "en", language, names_multilingual["en"]
            )
            logger.debug(
                "Translate name of node -> %s from -> '%s' (%s) to -> '%s' (%s)",
                current_node_id,
                name,
                "en",
                names_multilingual[language],
                language,
            )
        if (
            language in descriptions_multilingual
            and descriptions_multilingual["en"]
            and not descriptions_multilingual[language]
        ):
            descriptions_multilingual[language] = translator.translate(
                "en", language, descriptions_multilingual["en"]
            )
            logger.debug(
                "Translate description of node -> %s from -> '%s' (%s) to -> '%s' (%s)",
                current_node_id,
                name,
                "en",
                names_multilingual[language],
                language,
            )

    # Rename node multi-lingual:
    if not simulate:
        self.rename_node(
            current_node_id,
            name,
            description,
            names_multilingual,
            descriptions_multilingual,
        )

    # Get children nodes of the current node:
    results = self.get_subnodes(current_node_id, limit=200)["results"]

    # Recursive call of all subnodes:
    for result in results:
        self.volume_translator(
            result["data"]["properties"]["id"], translator, languages
        )